顯示包含「XML」標籤的文章。顯示所有文章
顯示包含「XML」標籤的文章。顯示所有文章

2011/02/28

Make HTTP / XML request in API and Parse result (PHP)

for美國郵政局,using simple XML request, include the XML within the url with the registered userID,
it will then return XML result in similar format
http://www.usps.com/webtools/htm/Track-Confirm.htm

Test Request #1

http://SERVERNAME/ShippingAPITest.dll?API=TrackV2&XML=

<TrackRequest USERID="xxxxxxxx">
<TrackID ID="EJ958083578US">
</TrackID>
</TrackRequest>

Example
$xml ='http://testing.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=';
$xml.= '<TrackRequest USERID="'.$usps_id.'">';
$xml.= '<TrackID ID="'.$usps_track_id.'">';
$xml.= '</TrackID></TrackRequest>';

$xml_file = urlencode($xml);

    if( ! $xml = simplexml_load_file($xml_file) )
    { 
        echo 'unable to load XML file';
    }
    else
    { 
        foreach( $xml as $user )
        {
            echo 'TrackSummary: '.$user->TrackSummary.'<br />';
for ($i=0;$i<count($user->TrackDetail);$i++){
echo 'TrackDetail: '.$user->TrackDetail[$i].'<br />';
}
        }
    }


EBay
SOAP API  request can be posted by CURL which is an extension in PHP.
E.g. ebay api, using CURL,data in xml and header can be make into HTTP request to the specific URL

 $endpoint = 'https://api.ebay.com/ws/api.dll';
    // create the xml request that will be POSTed
    $xmlRequest  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    $xmlRequest .= ".........";


    $session  = curl_init($endpoint);                       // create a curl session
    curl_setopt($session, CURLOPT_POST, true);              // POST request type
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($session, CURLOPT_POSTFIELDS, $xmlRequest); // set the body of the POST
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);    // return values as a string - not to std out
    $headers = array(
      'X-EBAY-API-COMPATIBILITY-LEVEL: 643',
      'X-EBAY-API-DEV-NAME: ...........
//input your required a/c info
      'X-EBAY-API-SITEID: 0',                                 // Site 0 is for US
      'Content-Type: text/xml;charset=utf-8'
    );
    curl_setopt($session, CURLOPT_HTTPHEADER, $headers);    //set headers using the above array of headers

    $responseXML = curl_exec($session);                     // send the request
    curl_close($session);

//    print_r($responseXML);

ebay (Alternative)

但以上的CODE太麻煩, 次次都要人手對番那串極長的xml request, 再insert對應不同api的parameter太費時了,  所以ebay 有sdk for php 給人下載, 名為PHP Toolkit with 527 Support
file名係EbatNs_1_0_527_0, 內置了所有api, 只要在config 輸入appid 等info便可即時調用

 $session = new EbatNs_Session('../EbatNsSamples/config/ebay.config.php');
 $cs = new EbatNs_ServiceProxy($session);
 // Set the Request type
 //#type $req GetSellerListRequestType
 $req = new GetSellerListRequestType();



PHP Toolkit Samples 有齊各api的sample code, copy & paste 改variable數值就可以了