I need to create payment module for opencart. The problem how to build xml output in php to post it to remote leasing server url: https://ecredit.leasing.com/eshop_test/UBLOnline.aspx?eshopdata=?
using post method.
I trying to build this xml:
<?xml version="1.0" encoding="UTF-8"?>
<ContractRequest xmlns="http://e-credit.ubl.lt/eshop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://e-credit.ubl.lt/eshop http://e-credit.leasing.com/eshop/contractrequest.xsd">
<SaleLogin>test</SaleLogin>
<SaleConditionID>111</SaleConditionID>
<Person>
<FirstName>John</FirstName>
<LastName>Jones</LastName>
</Person>
<Communication>
<StreetOrVillage>First</StreetOrVillage>
<City>New York</City>
<PostCode>21212</PostCode>
<Phone>+100000000</Phone>
<Email>john#mymail.com</Email>
</Communication>
<ContractDetails>
<CreditAmount>617.60</CreditAmount>
<CreditCurrency>USD</CreditCurrency>
</ContractDetails>
<OrderedItemsDetail>
<Item>
<Name>1 x HP 250 G5 UMA Celeron N3060 15.6 HD SVA, 1 x HP 15-r101na 15.6 HD Brightview flat (B), </Name>
<Amount>2pcs.</Amount>
<Price>617.60</Price>
<Currency>USD</Currency>
</Item>
</OrderedItemsDetail>
</ContractRequest>
I have tried create xml like this:
$XmlString = '<?xml version="1.0" encoding="UTF-8" ?>';
$XmlString .= '<ContractRequest
xmlns="http://e-credit.ubl.lt/eshop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://e-credit.ubl.com/eshop http://e-credit.leasing.com/eshop/contractrequest.xsd">';
$XmlString .= '<SaleLogin>' . $data['SaleLogin'] . '</SaleLogin>';
$XmlString .= '<SaleConditionID>' . $data['SaleConditionID'] . '</SaleConditionID>';
$XmlString .= '<Person>';
$XmlString .= '<FirstName>' . $data['first_name'] . '</FirstName>';
$XmlString .= '<LastName>' . $data['last_name'] . '</LastName>';
$XmlString .= '</Person>';
$XmlString .= '<Communication>';
$XmlString .= '<StreetOrVillage>' . $data['street'] . '</StreetOrVillage>';
$XmlString .= '<City>' . $data['city'] . '</City>';
$XmlString .= '<PostCode>' . $data['postcode'] . '</PostCode>';
$XmlString .= '<Phone>' . $data['telephone'] . '</Phone>';
$XmlString .= '<Email>' . $data['email'] . '</Email>';
$XmlString .= '</Communication>';
$XmlString .= '<ContractDetails>';
$XmlString .= '<CreditAmount>' . $data['amount'] . '</CreditAmount>';
$XmlString .= '<CreditCurrency>' . $data['currency'] . '</CreditCurrency>';
$XmlString .= '</ContractDetails>';
$XmlString .= '<OrderedItemsDetail>';
$XmlString .= '<Item>';
$XmlString .= '<Name>' . $data['description'] . '</Name>';
$XmlString .= '<Amount>' . $data['products_amount'] . '</Amount>';
$XmlString .= '<Price>' . $data['amount'] . '</Price>';
$XmlString .= '<Currency>' .$data['currency'] . '</Currency>';
$XmlString .= '</Item>';
$XmlString .= '</OrderedItemsDetail>';
$XmlString .= '</ContractRequest>';
and after :
$url = https://ecredit.leasing.com/eshop_test/UBLOnline.aspx?eshopdata=?;
$header = array();
$header[] = 'Content-Type: text/xml';
$header[] = 'Content-Length: ' . strlen($XmlString);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, &url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $XmlString);
///////////////////////
$response = curl_exec($ch);
curl_close($ch);
$XmlString = simplexml_load_string($response);
//create object to use as json
$json = array();
$json['redirect'] = $this->url->link('checkout/success', '', true);
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
but this does not work... sad.... what i miss?
how to create properly xml request and post it to url?
You already has some tips (and maybe your answer) in the comments, but here is some thoughts on what you should do to improve your code and also help others to help you.
PHP gives you some good resources to create XML, you should use them. I recommend DOMDocument. Below is a starter code to your example.
$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$namespace = 'http://e-credit.ubl.lt/eshop';
$contractRequest = $dom->createElement('ContractRequest');
$contractRequest->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', $namespace);
$saleLogin = $dom->createElement('SaleLogin', 'test');
$saleConditionID = $dom->createElement('SaleConditionID', '111');
$contractRequest->appendChild($saleLogin);
$contractRequest->appendChild($saleConditionID);
$dom->appendChild($contractRequest);
//you got the idea...
For the curl part, first change the first setopt to curl_setopt($ch, CURLOPT_URL, $url);. Now, before close your curl handle, insert the following code:
if($response === false)
{
echo 'Curl error: ' . curl_error($ch);
}
If it not work, you can debug your curl request. This another question may help you.
UPDATE
I think that the use of curl for your request is the right option, but, as you requested in the comment, here is an option if your curl request continues to fail.
$payload = array();
$payload['header'] = 'Content-Type: text/xml';
$payload['header'] .= 'Content-Length: ' . strlen($XmlString);
$payload['content'] = is_array($XmlString) ? http_build_query($XmlString) : $XmlString;
$payload['method'] = 'POST';
$payloadContext = stream_context_create(array('http' => $payload));
$result = file_get_contents($url, false, $payloadContext);
if ($result === false) {
print_r ("Error in your request. Check logs for more information");
}
As I said, its just an option, but curl remains a good one, you just need to correct it.
Related
I am trying to convert the sitemap.xml into sitemap.xml.gz , The pages I am extracting from the database , it is converting into sitemap.xml , but when I am trying to compress this is not working . this is my code it is making the file damage .
header('content-type: application/x-gzip');
header('Content-Disposition: attachment; filename="sitemap.xml.gz"');
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>';
$xmlString .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
include("admin/functions/dbconfig.php");
$sql = "select * from zz where aa between 1 and 30000";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)){
$url = $row["aa"];
$xmlString .= '<url>';
$xmlString .= '<loc>http://mynewdomain.com/page.php?word='.htmlentities($url).'</loc>';
$xmlString .= '<lastmod>'.date("Y-m-d").'</lastmod>';
$xmlString .= '<changefreq>monthly</changefreq>';
$xmlString .= '<priority>0.5</priority>';
$xmlString .= '</url>';
}
$xmlString .= '</urlset>';
gzwrite("compress", gzencode($xmlString));
gzclose("compress");
I am trying to create XML files via PHP for Googles Merchant center.
I had previously done the same with creating a sitemap but now am having issues.
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>';
$xmlString .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
$xmlString .= '<url>';
$xmlString .= '<loc>example.com</loc>';
$xmlString .= '<lastmod>'.date(DATE_ATOM,time()).'</lastmod>';
$xmlString .= '<changefreq>daily</changefreq>';
$xmlString .= '<priority>1.0</priority>';
$xmlString .= '</url>';
$xmlString .= '</urlset>';
$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xmlString);
$dom->save('../sitemap.xml');
This is more or less what I have to create my sitemap except I am obviously creating more URLs by querying my database.
But then I do more or less the exact same thing for my product feed but it does not work.
$xmlString .= '<?xml version="1.0" encoding="UTF-8"?>';
$xmlString .= '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">';
$xmlString .= '<channel>';
$xmlString .= '<title>Product Feed</title>';
$xmlString .= '<link>https://www.example.com/</link>';
$xmlString .= '<description>Product Feed</description>';
$xmlString .= '<item>';
$xmlString .= '<g:id>'.$product_id.'</g:id>';
$xmlString .= '<title>'.$product_name.'</title>';
$xmlString .= '<description>'.$product_description.'</description>';
$xmlString .= '<link>https://www.example.com/product/'.$product_url.'</link>';
$xmlString .= '<g:condition>new</g:condition>';
$xmlString .= '<g:price>'.$rounded_lowest_sale_price.'</g:price>';
$xmlString .= '<g:availability>in stock</g:availability>';
$xmlString .= '<g:image_link>https://www.example.com/media/product_images/'.$first_image.'</g:image_link>';
$xmlString .= '<g:mpn>'.$model_no.'</g:mpn>';
$xmlString .= '<g:brand>'.$brand.'</g:brand>';
$xmlString .= '<g:google_product_category>Business & Industrial > Material Handling</g:google_product_category>';
$xmlString .= '</item>';
}
$xmlString .= '</channel>';
$xmlString .= '</rss>';
echo $xmlString;
$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xmlString);
$dom->save('../product_feeds/product_feed_int.xml');
It saves the XML file but all it contains is:
<?xml version="1.0"?>
without even the UTF-8 encoding.
If you don't use DOMDocument to create the xml you can put your string directly into a file
file_put_contents('../product_feeds/product_feed_int.xml', $xmlString);
consider to use & for & in
Business & Industrial
This might Help
<?php
$xmldoc = new DOMDocument();
$xmldoc->encoding = 'utf-8';
$xmldoc->xmlVersion = '1.0';
$xmldoc->formatOutput = true;
$xml_file_name = 'xmlfile.xml';
$root = $xmldoc->createElement('Cars');
$car_node = $xmldoc->createElement('car');
$attr_movie_id = new DOMAttr('car_model', 'ritz');
$car_node->setAttributeNode($attr_movie_id);
$child_node_title = $xmldoc->createElement('Make', 'Maruti');
$car_node->appendChild($child_node_title);
$child_node_year = $xmldoc->createElement('Year', 2012);
$car_node->appendChild($child_node_year);
$child_node_genre = $xmldoc->createElement('Type', 'Hatchback');
$car_node->appendChild($child_node_genre);
$child_node_ratings = $xmldoc->createElement('Ratings', 6.2);
$car_node->appendChild($child_node_ratings);
$root->appendChild($car_node);
$xmldoc->appendChild($root);
$xmldoc->save($xml_file_name);
echo "$xml_file_name created";
?>
it's a few days that I am trying to update the quantity of inventory on Amazon through php and Amazon MWS in php (without using MWS APIs because in my opinion are out of dated)
Here is my code:
$param = array();
$param['AWSAccessKeyId'] = $this->CHIAVE_ACCESSO;
$param['Action'] = 'SubmitFeed';
$param['Merchant'] = $this->SELLER_ID;
$param['FeedType'] = '_POST_INVENTORY_AVAILABILITY_DATA_';
$param['SignatureMethod'] = 'HmacSHA256';
$param['SignatureVersion'] = '2';
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version'] = '2009-01-01';
$params['MarketplaceId.Id.1'] = $this->MARCKETPLACE_IT;
$params['MarketplaceId.Id.2'] = $this->MARCKETPLACE_UK;
$params['MarketplaceId.Id.3'] = $this->MARCKETPLACE_ES;
$params['MarketplaceId.Id.4'] = $this->MARCKETPLACE_DE;
$params['MarketplaceId.Id.5'] = $this->MARCKETPLACE_FR;
$param['PurgeAndReplace'] = 'false';
foreach ($param as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
}
$amazon_feed = '<?xml version="1.0" encoding="utf-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>' .$this->SELLER_ID. '</MerchantIdentifier>
</Header>
<MessageType>Inventory</MessageType>
<Message>
<MessageID>1</MessageID>
<OperationType>Update</OperationType>
<Inventory>
<SKU>'.$sku.'</SKU>
<Quantity>'.$qty.'</Quantity>
</Inventory>
</Message>
</AmazonEnvelope>';
sort($url);
$arr = implode('&', $url);
$sign = 'POST' . "\n";
$sign .= 'mws.amazonservices.it' . "\n";
$sign .= '/Feeds/'.$param['Version'].'' . "\n";
$sign .= $arr;
$signature = hash_hmac("sha256", $sign, $this->secretKey, true);
$httpHeader = array();
$httpHeader[] = 'Transfer-Encoding: chunked';
$httpHeader[] = 'Content-Type: application/xml';
$httpHeader[] = 'Content-MD5: ' . base64_encode(md5($amazon_feed, true));
//$httpHeader[] = 'x-amazon-user-agent: MyScriptName/1.0';
$httpHeader[] = 'Expect:';
$httpHeader[] = 'Accept:';
$signature = urlencode(base64_encode($signature));
$link = "https://mws.amazonservices.it/Feeds/".$param['Version']."?";
$link .= $arr . "&Signature=" . $signature;
echo $link;
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $amazon_feed);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$errors=curl_error($ch);
curl_close($ch);
echo '<pre>';
print_r($response); //xml response
The response is
50691017150_POST_INVENTORY_AVAILABILITY_DATA_2016-12-15T10:00:09+00:00_SUBMITTED_47843855-c5fb-4db9-bc3c-1ccd0aff4169
But When I go on the Amazon Inventory I cannot see any changes. I've tried also to wait some days but nothing changes.
What I'm doing wrong?
Thanks in advance for help!
Using MWS Scratchpad the error I have is the following
<?xml version="1.0" encoding="UTF-8"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.02</DocumentVersion>
<MerchantIdentifier>A2PDC8GCZHAL2D</MerchantIdentifier>
</Header>
<MessageType>ProcessingReport</MessageType>
<Message>
<MessageID>1</MessageID>
<ProcessingReport>
<DocumentTransactionID>50691017150</DocumentTransactionID>
<StatusCode>Complete</StatusCode>
<ProcessingSummary>
<MessagesProcessed>1</MessagesProcessed>
<MessagesSuccessful>0</MessagesSuccessful>
<MessagesWithError>1</MessagesWithError>
<MessagesWithWarning>0</MessagesWithWarning>
</ProcessingSummary>
<Result>
<MessageID>1</MessageID>
<ResultCode>Error</ResultCode>
<ResultMessageCode>13013</ResultMessageCode>
<ResultDescription>This SKU does not exist in the Amazon.com catalog. Your inventory data was not processed. For reasons why, and help fixing this, see http://sellercentral.amazon.it/gp/errorcode/13013</ResultDescription>
<AdditionalInfo>
<SKU>887235757035</SKU>
</AdditionalInfo>
</Result>
</ProcessingReport>
</Message>
but this sku exists in my catalog
The actual response is alway XML from MWS, where you can see that 50691017150 is actually your FeedSubmissionId.
When you submit a feed MWS gives you back with a FeedSubmissionId, by which you can track what happened to your feed.
If you go to MWS Scratchpad, you can get the feed result.
Enter the required credentials in Authentication form and select feed as Sezione AP and GetFeedSubmissionResult as Operation.
You will be than asked for FeedSubmissionId which you already have.
See what happened to that feed and why did it fail?
You are passing Marketplace Ids , which means that the sku is available there. But in your case it might not be available in any one of these. And MarketplaceId is optional, you can remove
$params['MarketplaceId.Id.1'] = $this->MARCKETPLACE_IT;
$params['MarketplaceId.Id.2'] = $this->MARCKETPLACE_UK;
$params['MarketplaceId.Id.3'] = $this->MARCKETPLACE_ES;
$params['MarketplaceId.Id.4'] = $this->MARCKETPLACE_DE;
$params['MarketplaceId.Id.5'] = $this->MARCKETPLACE_FR;
I am using amazon api for update product's quantity using "_POST_INVENTORY_AVAILABILITY_DATA_" feedtype like,
<?xml version="1.0" encoding="utf-8" ?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>$merchantID</MerchantIdentifier>
</Header>
<MessageType>Inventory</MessageType>
<Message>
<MessageID>1</MessageID>
<OperationType>Update</OperationType>
<Inventory>
<SKU>$SKU</SKU>
<Quantity>8</Quantity>
</Inventory>
</Message>
</AmazonEnvelope>
<?xml version="1.0"?>
<SubmitFeedResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">
<SubmitFeedResult>
<FeedSubmissionInfo>
<FeedSubmissionId>6791310806</FeedSubmissionId>
<FeedType>_POST_INVENTORY_AVAILABILITY_DATA_</FeedType>
<SubmittedDate>2013-03-21T19:48:37+00:00</SubmittedDate>
<FeedProcessingStatus>_SUBMITTED_</FeedProcessingStatus>
</FeedSubmissionInfo>
</SubmitFeedResult>
<ResponseMetadata>
<RequestId>fd07bf18-4f6a-4786-bdf9-9d4db50956d0</RequestId>
</ResponseMetadata>
</SubmitFeedResponse>
but when i try to update 15k or more products at a time by loading products using magento collection quantity not updating in amazon after few hours also. Is it right method or do i need to use any other method?
Can anyone help me?
Thanks in advance.
Try Using _POST_FLAT_FILE_PRICEANDQUANTITYONLY_UPDATE_DATA_ feedtype and send a CSV file (tab delimited) in the body of the https request instead of an XML file. The first line of the csv should be: sku price quantity (separated by tabs) followed by lines containing the values (separated by tabs).
Quoting Amazon MWS API:
Feed size is limited to 2,147,483,647 bytes (2^31 -1) per feed. If you
have a large amount of data to submit, you should submit feeds smaller
than the feed size limit by breaking up the data, or submit the feeds
over a period of time. One good practice is to submit feeds with a
size limit of 30,000 records/items or submit feeds over a period of
time, such as every few hours.
$feed = '<?xml version="1.0" encoding="utf-8" ?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>AG7AH5X9UOHEC</MerchantIdentifier>
</Header>
<MessageType>Inventory</MessageType>
<Message>
<MessageID>1</MessageID>
<OperationType>Update</OperationType>
<Inventory>
<SKU>UK-BBD10002</SKU>
<Quantity>4</Quantity>
<FulfillmentLatency>15</FulfillmentLatency>
</Inventory>
</Message>
<Message>
<MessageID>2</MessageID>
<OperationType>Update</OperationType>
<Inventory>
<SKU>UK-BBD10003</SKU>
<Quantity>6</Quantity>
<FulfillmentLatency>14</FulfillmentLatency>
</Inventory>
</Message>
</AmazonEnvelope>';
$feedHandle = #fopen('php://temp', 'rw+');
fwrite($feedHandle, $feed);
rewind($feedHandle);
$param['AWSAccessKeyId'] = Configure::read('AWS_ACCESS_KEY');
$param['Action'] = 'SubmitFeed';
$param['SellerId'] = Configure::read('SELLER_ID');
$param['SignatureMethod'] = Configure::read('SIGNATURE_METHOD');
$param['SignatureVersion'] = Configure::read('SIGNATURE_VERSION');
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version'] = '2009-01-01';
$param['FeedType'] = $FeedType;
$param['FeedContent'] = stream_get_contents($feedHandle);
$param['ContentMd5'] = base64_encode(md5(stream_get_contents($feedHandle), true));
$param['MarketplaceIdList.Id.1'] = $MARKETPLACE_ID; //FR
//$param['MarketplaceIdList.Id.2'] = 'A1F83G8C2ARO7P'; //GB
ksort($param);
$MARKETPLACE_URL = 'mws.amazonservices.co.uk';
$secret = Configure::read('SECRET_KEY');
$url = array();
foreach ($param as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
}
ksort($url);
$arr = implode('&', $url);
$sign = 'GET' . "\n";
$sign .= ''.$MARKETPLACE_URL.'' . "\n";
$sign .= '/Feeds/2009-01-01' . "\n";
$sign .= $arr;
$signature = hash_hmac("sha256", $sign, $secret, true);
$signature = urlencode(base64_encode($signature));
$link = "https://".$MARKETPLACE_URL."/Feeds/2009-01-01?";
$link .= $arr . "&Signature=" . $signature;
$httpHeader = array();
$httpHeader[] = 'Content-Type: application/xml';
$httpHeader[] = 'Content-MD5: ' . base64_encode(md5(stream_get_contents($feedHandle), true));
$httpHeader[] = 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'];
$httpHeader[] = 'Host: ' . $MARKETPLACE_URL;
ksort($httpHeader);
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
#fclose($feedHandle);
print_r($response);
exit;
I have been working on the Saia Carrier API and have it giving me values albeit they are not very appealing. I would like to parse the values and put them into variables so I can display them neatly in a table.
Here is the code:
<?php
$postdata = '<?xml version="1.0" encoding="utf-8"?>
<Create>
<UserID>XXX</UserID>
<Password>XXX</Password>
<TestMode>Y</TestMode>
<BillingTerms>Prepaid</BillingTerms>
<AccountNumber>XXX</AccountNumber>
<Application>Outbound</Application>
<OriginZipcode>44483</OriginZipcode>
<DestinationZipcode>90077</DestinationZipcode>
<Details>
<DetailItem>
<Weight>100</Weight>
<Class>85</Class>
</DetailItem>
</Details>
</Create>';
$url = "http://www.saiasecure.com/webservice/ratequote/xml.aspx";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-type: text/xml'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close ($ch);
$status = $info['http_code'];
echo $status;
echo '<pre>';
print_r($response);
?>
I got it.
Just added:
$xml = simplexml_load_string($response);
and changed:
print_r($response);
to:
print_r($xml);
I've always used PHP's SimpleXML library: http://php.net/manual/en/book.simplexml.php
This creates a pretty basic object that is easy to use and traverse.
This is an example of traversing with the children() function from the site: http://www.php.net/manual/en/simplexmlelement.children.php
<?php
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');
foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];
foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';
foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
?>
You can also retrieve attributes via the attributes() function: http://www.php.net/manual/en/simplexmlelement.attributes.php
<?php
$string = <<<XML
<a>
<foo name="one" game="lonely">1</foo>
</a>
XML;
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>