0

UPDATE

I added some logging and my first log, the response, is returning the XML. But after I put the response in simplexml_load_string and then log that variable, it is empty in my log.

    $client = new Client();
    $res = $client->request('GET', $url);
    log_info($res->getBody()-getContents());

    $orders = simplexml_load_string($res->getBody()->getContents());
    log_info($orders);

-------

------

Original Question

I am trying to parse the XML at the below here using SimpleXML. In my code, I have:

    $orders = simplexml_load_string($res->getBody()->getContents());
    $orders->getNamespaces(true);

    foreach ($orders->TrackInfo as $order) {
        // logic
    }

This was working for me for the last few days but now I am getting the following error Error: Call to a member function getNamespaces() on boolean. Not sure what I am doing wrong here.


XML

<?xml version="1.0" encoding="UTF-8"?>
<TrackResponse>
   <TrackInfo ID="9405509205328001086959">
      <Error>
         <Number>-2147219283</Number>
         <Description>A status update is not yet available on your Priority Mail&lt;SUP&gt;&amp;reg;&lt;/SUP&gt; package. It will be available when the shipper provides an update or the package is delivered to USPS. Check back soon. Sign up for Informed Delivery&lt;SUP&gt;&amp;reg;&lt;/SUP&gt; to receive notifications for packages addressed to you.</Description>
         <HelpFile />
         <HelpContext />
      </Error>
   </TrackInfo>
</TrackResponse>
Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82
burtonLowel
  • 734
  • 7
  • 17
  • `simplexml_load_string()` can return false when it fails to load the XML, although the XML you show seems valid. You will need to check what `$res->getBody()->getContents()` is giving when it fails. – Nigel Ren Jan 26 '20 at 07:44
  • @NigelRen yep, I checked the XML by logging it. I did `log_info($orders)` right after I set `$orders = simplexml_load_string($res->getBody()->getContents());` It's logging the exact XML that I pasted. That is what has me stumped. – burtonLowel Jan 26 '20 at 07:49
  • making an EDIT now – burtonLowel Jan 26 '20 at 07:56
  • The return value of `simplexml_load_string()` is a `SimpleXMLElement` and it cannot be treated as a string. Use `$orders->asXML()` instead. – miken32 Jan 27 '20 at 02:01
  • As an aside: `$orders->getNamespaces(true);` on its own doesn't do anything. It's a function for getting information out of the object, but you're not doing anything with the information. – IMSoP Jan 29 '20 at 12:34

0 Answers0