phpsimplexmlcxml

Can't access attributes from XML response using simplexml_load_string


I'm trying to use simplexml_load_string to get the Status and Text values from the following XML response;

<?xml version="1.0" encoding="utf-16"?>    
<cXML payloadID="online" xml:lang="en" timestamp="2017-12-04T15:57:47.6693296+00:00">
  <Response>
    <Status code="402" text="&#x9;&#xA; product 325552not in customer[20690]  pricelist" />
  </Response>
</cXML>

In my PHP code I am getting the XML above from $reply:

$reply = curl_exec($curl);

I am then using simplexml_load_string like so:

$responseData = simplexml_load_string($reply);
echo 'Sync Order - '. $order->getIncrementId() . ' Status '. $responseData->Response->Status['code'] .' - '. $responseData->Response->Status['text'];

But this doesn't seem to get the code and text from the XML response above. Wondering if anyone has any ideas to help?

Thank you.

Note: The cXML is correct.


Solution

  • I've tried it with the added xml header and UTF-16 encoding bit and it fails to load with an error...

    PHP Warning: simplexml_load_string(): Entity: line 1: parser error : Document labelled UTF-16 but has UTF-8 content in

    A simple but crude way round it is to change the UTF in the xml element to UTF8...

    $reply = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $reply);
    $responseData = simplexml_load_string($reply);
    

    This then gives the output as expected...

     Status 402 -   
     product 325552not in customer[20690]  pricelist