如何将 XML 输出解析为单行

How to parse XML output into single line

我正在尝试设置 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
        )
    )
)

您必须将 simpleXML 对象转换为字符串。 试试下面的代码:

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

您的描述在 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 $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;

}
?>