0

I've come across a weird but apparently valid XML string that I'm being returned by an API. I've been parsing XML with SimpleXML because it's really easy to pass it to a function and convert it into a handy array.

The following is parsed incorrectly by SimpleXML:

<?xml version="1.0" standalone="yes"?>
<Response>
    <CustomsID>010912-1
        <IsApproved>NO</IsApproved>
        <ErrorMsg>Electronic refunds...</ErrorMsg>
    </CustomsID>
</Response>

Simple XML results in:

SimpleXMLElement Object ( [CustomsID] => 010912-1 )

Is there a way to parse this in XML? Or another XML library that returns an object that reflects the XML structure?

2 Answers 2

1

That is an odd response with the text along with other nodes. If you manually traverse it (not as an array, but as an object) you should be able to get inside:

<?php
    $xml = '<?xml version="1.0" standalone="yes"?>
    <Response>
        <CustomsID>010912-1
            <IsApproved>NO</IsApproved>
            <ErrorMsg>Electronic refunds...</ErrorMsg>
        </CustomsID>
    </Response>';

    $sObj = new SimpleXMLElement( $xml );

    var_dump( $sObj->CustomsID );

    exit;
?>

Results in second object:

object(SimpleXMLElement)#2 (2) {
  ["IsApproved"]=>
  string(2) "NO"
  ["ErrorMsg"]=>
  string(21) "Electronic refunds..."
}
Sign up to request clarification or add additional context in comments.

1 Comment

The issue turned out to be I was deconstructing it with php's get_object_vars() function. This works 90% of the time but chokes in this instance because of how SimpleXML holds the data. So not the fault of SimpleXML and manually traversing it will do the trick.
0

You already parse the XML with SimpleXML. I guess you want to parse it into a handy array which you not further define.

The problem with the XML you have is that it's structure is not very distinct. In case it does not change much, you can convert it into an array using a SimpleXMLIterator instead of a SimpleXMLElement:

$it    = new SimpleXMLIterator($xml);
$mode  = RecursiveIteratorIterator::SELF_FIRST;
$rit   = new RecursiveIteratorIterator($it, $mode);
$array = array_map('trim', iterator_to_array($rit));

print_r($array);

For the XML-string in question this gives:

Array
(
    [CustomsID] => 010912-1
    [IsApproved] => NO
    [ErrorMsg] => Electronic refunds...
)

See as well the online demo and How to parse and process HTML/XML with PHP?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.