解析XML响应

时间:2013-09-05 20:21:30

标签: php api curl

我一直在研究Saia Carrier API并让它给我价值,尽管它们不是很吸引人。我想解析这些值并将它们放入变量中,以便我可以将它们整齐地显示在表格中。

以下是代码:

<?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);

?>

2 个答案:

答案 0 :(得分:0)

我一直使用PHP的SimpleXML库:http://php.net/manual/en/book.simplexml.php

这创建了一个易于使用和遍历的非常基本的对象。

这是使用网站children()功能遍历的示例: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'];
        }
    }
}
?>

您还可以通过attributes()函数检索属性: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";
}
?>

答案 1 :(得分:0)

我明白了。

刚补充说:

 $xml = simplexml_load_string($response); 

并改变了:

print_r($response);

为:

 print_r($xml);