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";
}
?>
Related
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.
My XML to be parsed is in this format:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header />
<env:Body>
<n0:ZFM_PAYSLIP1Response xmlns:n0="urn:sap-com:document:sap:rfc:functions">
<LS_EMP_PAYSLIP_DATA>
<ZEMP_NO>00199999</ZEMP_NO>
<ZEMP_NAME>AJ KUMAR</ZEMP_NAME>
<ZSAL_MONTH>JUL-2016</ZSAL_MONTH>
<ZBASIC_PAY>57240.0</ZBASIC_PAY>
<ZGROSS_PAY>145062.29</ZGROSS_PAY>
<ZNET_PAY>50728.0</ZNET_PAY>
<ZINCOME_TAX>25858.0</ZINCOME_TAX>
<ZLEAVE_ENCASH>0.0</ZLEAVE_ENCASH>
<ZDUTY_PAY>41976.0</ZDUTY_PAY>
<ZDA>56950.4</ZDA>
<ZPERKS>26330.4</ZPERKS>
<ZHRA>11448.0</ZHRA>
<ZTOT_DEDUCTIONS>94334.29</ZTOT_DEDUCTIONS>
<ZCPF>12787.0</ZCPF>
<ZVPF>50000.0</ZVPF>
<ZLIC>0.0</ZLIC>
<ZTHRIFT_FUND>0.0</ZTHRIFT_FUND>
<ZGRP_INS>160.0</ZGRP_INS>
<ZPROF_TAX>200.0</ZPROF_TAX>
<ZDUTY_DAYS>18</ZDUTY_DAYS>
<ZWEEK_OFF>4</ZWEEK_OFF>
<ZFL />
<ZCL />
<ZEL />
<ZFPL />
<ZHPL>8</ZHPL>
<ZCML />
<ZEOL />
<ZUAB />
<ZDEISGNATION>Sr.Manager(IT)</ZDEISGNATION>
<ZDEPT_CODE>03007900</ZDEPT_CODE>
<ZCL_BAL>3</ZCL_BAL>
<ZEL_BAL>270.5</ZEL_BAL>
<ZHPL_BAL>180</ZHPL_BAL>
</LS_EMP_PAYSLIP_DATA>
</n0:ZFM_PAYSLIP1Response>
</env:Body> </env:Envelope>
I am using PHP curl to get data from remote with
this PHP code :
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://hostanme.tld/ERP_PAY_XML.xml');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//echo $result;
curl_close($ch);
$xml = simplexml_load_string($result);
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['env']);
echo "<br> len-soap : " . $soap;
$getaddressresponse = $soap->Body->children($ns['n0']);
foreach ($getaddressresponse->getLocationForGroupResponse->children($ns['n0']) as $item)
{
$item = $item->children();
echo $item->address . '<br />';
}
?>
but still I am not getting any result. Anybody please help..
Is there any other way to parse XML to an object..
I want to extract url data just like as facebook. For that I am using php DOMDocument.While retrieving the DOM content i.e while retrieving "title" the DOMDocument is returning 0 elements. Here is my code
<?php
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" ?>';
//$url = $_REQUEST["url"];
$url = "http://business.tutsplus.com/articles/how-to-set-up-your-first-magento-store--fsw-43137";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
$data = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
#$dom->loadHTML($data);
$title = $dom->getElementsByTagName("title");
//$title = $dom->find("title");
echo "<urlData>";
echo "<title>";
echo $title->length;
echo "</title>";
echo "</urlData>";
?>
Here $title->length is returning 0 elements. What is the problem?
I'm tring to process xml (website) into php array.
I have tried the following code which works for everyting in results but i need to get the totalpage which i'm not able to see how I can do this.
function get_content($url)
/// basically opens the page and stores it as a variable. Buggered if I know how it works!
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
$string = NULL;
$ch = NULL;
$url = NULL;
}
$url = "url";
$content = get_content($url);
$content_x = explode("<result>", $content);
foreach ($content_x as $item)
{
$p1 = strpos($item, '<title>');
$p2 = strpos($item, '</title>');
$l1 = $p2 - $p1;
echo '<br>'.$title = substr($item, $p1, $l1);
}
xml site feed
<?xml version="1.0" encoding="UTF-8"?>
<response version="2">
<totalpage>1005</totalpage>
<results>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
........so on
<results>
</response>
I need to get totalpage and everyting in results
How do get totalpage and is they better way to process the results
You absolutely should not be using string manipulation to try to parse XML. There are any number of PHP libraries that can do this. I might recommend SimpleXML.
Usage would be:
$xml = simplexml_load_string($content);
$totalpage = $xml->response->totalpage;
I have to parse an xml file that contains various namespaces.
I have already registered the namespaces.
My problem is that I cannot extract the data from the cal:location block.
For example i need the vcard:street-address or the vcard:postal-code.
XML - Example:
<channel>
<title>Veranstaltungen zum Thema Markt+Bauer vom 05.05.2011 bis 05.05.2012</title>
<link>https://www.wien.gv.at/vadb/internet/AdvPrSrv.asp?Layout=VAErgebnis_neu&Type=S&ganzjaehrig=ja</link>
<description> Veranstaltungen zum Thema Markt+Bauer vom 05.05.2011 bis 05.05.2012 </description>
<lastBuildDate>Sa,05 Jän 2013 17:38:05 GMT</lastBuildDate>
<ManagingEditor>event#ma55.wien.gv.at</ManagingEditor>
<language>de-AT</language>
<dc:license>http://data.wien.gv.at/nutzungsbedingungen</dc:license>
<dc:rightsHolder>Stadt Wien</dc:rightsHolder>
<item>
<title>Bauernmarkt am Karmelitermarkt</title>
<link>https://www.wien.gv.at/vadb/internet/AdvPrSrv.asp?Layout=VAErgebnis_neu&Type=K&ID=256811&return=</link>
<guid isPermaLink="false">https://www.wien.gv.at/vadb/internet/AdvPrSrv.asp?Layout=VAErgebnis_neu&Type=K&ID=256811&return=</guid>
<description><![CDATA[
<p>07.01.2011 bis 31.12.2011<br />
08:00 bis 13:00<br />
Karmelitermarkt<br />http://www.wiener-maerkte.at</p><p>Spezieller Bauernmarkt mit köstlichen naturreinen Produkten.</p>]]>
</description>
<category>Kulinarischer Markt</category>
<dc:subject>Kulinarischer Markt</dc:subject>
<cal:dtstart>2011-01-07T00:00:00+01:00</cal:dtstart>
<cal:dtend>2011-12-31T00:00:00+01:00</cal:dtend>
<cal:byday>Fr, Sa</cal:byday>
<cal:byhour>08</cal:byhour>
<cal:byminute>00</cal:byminute>
<cal:location>
<vcard:fn>Karmelitermarkt</vcard:fn>
<vcard:street-address>Haidgasse 1</vcard:street-address>
<vcard:postal-code>1020</vcard:postal-code>
<vcard:tel/>
<vcard:fax/>
<vcard:email>office#wiener-maerkte.at</vcard:email>
<vcard:url>http://www.wiener-maerkte.at</vcard:url>
</cal:location>
<cal:organizer>
<vcard:fn>Wiener Einkaufsstraßen-Management</vcard:fn>
<vcard:street-address>Hietzinger Kai 133</vcard:street-address>
<vcard:postal-code>1130</vcard:postal-code>
<vcard:tel>0043-1/514 50-6700</vcard:tel>
<vcard:fax>0043-1/514 50-6749</vcard:fax>
<vcard:email/>
<vcard:url>http://www.einkaufsstrassen.at</vcard:url>
</cal:organizer>
</item>
</channel>
My PHP - Code:
<?php
function download_feed($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_feed('xml - Example');
$oXML = new SimpleXMLElement($sXML);
foreach($oXML->channel->item as $oDocument){
$title = $oDocument->title;
$url = $oDocument->link;
$namespaces = $oDocument->getNameSpaces(true);
$cal = $oDocument->children($namespaces['cal']);
$vcard = $cal->children($namespaces['vcard']);
$dc = $oDocument->children($namespaces['dc']);
$georss = $oDocument->children($namespaces['georss']);
$byday = $cal->byday;
//var_dump($vcard);
$attrs = $oDocument->getElementsByTagName("vcard:fn");
$streetAddress = $oDocument->{'cal:location'}->{'vcard:fn'};
echo $title . "<br>" . $url . "<br>" . $byday. "<br>" . $streetAddress. "<br><br>";
}
?>
You've misunderstood the purpose of the ->children() method: it doesn't "register" namespaces, it selects them for immediate use.
So to get to <cal:location>, you can use $oDocument->children($namespaces['cal'])->location, and the <vcard:fn> inside that would be $oDocument->children($namespaces['cal'])->location->children($namespaces['vcard'])->fn
Since PHP 5.2, you can also use prefixes directly, rather than looking up their URLs, by giving the ->children() method an extra parameter of true: $oDocument->children('cal', true)->location->children('vcard', true)->fn