Search code examples
phpxmlsimplexml

How to parse XML output into single line


I am trying to setup a PHP code to use a XML API to contact Kunaki to get shipping prices. I try to parse the response via this code but get no output.

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

I am not sure what I am doing wrong, any help would be appreciated to figure out how to output this.

This is the output I get in 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
        )
    )
)

Solution

  • You have to cast simpleXML Object to a string. Try the code below:

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

    OUTPUT -

    2-5 business days will cost - 0.66

    1-5 business days will cost - 17.17

    2 business days will cost - 30.42

    1 business day will cost - 50.17