如何将XML输出解析为单行

时间:2017-07-06 00:34:57

标签: php xml simplexml

我正在尝试设置PHP代码以使用XML API与Kunaki联系以获取运费。我尝试通过此代码解析响应,但没有输出。

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';

$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml);
echo $xml->Description[3]->Description;
//print_r($xml); Debug line to make sure xml is outputing
?>

我不确定我做错了什么,任何帮助都会被理解为如何输出这个。

这是我在XML中获得的输出

SimpleXMLElement Object (
    [ErrorCode] => 0
    [ErrorText] => success
    [Option] => Array (
        [0] => SimpleXMLElement Object (
            [Description] => USPS First Class Mail
            [DeliveryTime] => 2-5 business days
            [Price] => 0.66
        )
        [1] => SimpleXMLElement Object (
            [Description] => UPS Ground
            [DeliveryTime] => 1-5 business days
            [Price] => 17.17
        )
        [2] => SimpleXMLElement Object (
            [Description] => UPS 2nd Day Air
            [DeliveryTime] => 2 business days
            [Price] => 30.42
        )
        [3] => SimpleXMLElement Object (
            [Description] => UPS Next Day Air Saver
            [DeliveryTime] => 1 business day
            [Price] => 50.17
        )
    )
)

3 个答案:

答案 0 :(得分:0)

您必须将simpleXML Object强制转换为字符串。 请尝试以下代码:

foreach ($xml->Option as $opt) {
    print "<br>";
    echo $value = (string)$opt->DeliveryTime." will cost - ".(string)$opt->Price;

}

输出 -

2-5个工作日将花费 - 0.66

1-5个工作日将花费--17.17

2个工作日将花费 - 30.42

1个工作日将花费 - 50.17

答案 1 :(得分:0)

您的描述位于Option元素内,您需要对其进行迭代。

$xml = new simplexmlelement($xml);
foreach($xml->Option as $options){
     echo $options->Description . "\n";
}

演示:https://eval.in/828259

要获得第四个描述,您可以执行以下操作:

echo $xml->Option[3]->Description->__tostring();

演示(v2):https://eval.in/828268

答案 2 :(得分:0)

我终于在睡觉之后想出来了。我做错了是我在代码中有2 $ xml。当我将其更改为$ xml2时,它解决了问题。如果需要,这是帮助任何人的最终代码。

<?php
$context  = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'http://kunaki.com/HTTPService.ASP?RequestType=ShippingOptions&State_Province=NY&PostalCode=11204&Country=United+States&ProductId=PX0012345&Quantity=1&ProductId=PX04444444&Quantity=1&ResponseType=xml ';
file_put_contents('output.xml', ob_get_contents());
$xml = file_get_contents($url, false, $context);
$xml2 = simplexml_load_string($xml);
foreach ($xml2->Option as $opt) {
    print "<br>";
    echo $value = (string)$opt->DeliveryTime." will cost - ".(string)$opt->Price;

}
?>