简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM