William W
William W

Reputation: 1806

PHP SimpleXML Element parsing issue

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?

Upvotes: 0

Views: 160

Answers (2)

hakre
hakre

Reputation: 198214

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

Upvotes: 0

Evan
Evan

Reputation: 63

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..."
}

Upvotes: 1

Related Questions