Search code examples
phpxmlsimplexml

SimpleXMLElement - Trying to get property of non-object


In a response we receive an xml file, then convert to SimpleXMLElement, then access the elements and attributes as needed. However, we are getting "Trying to get property of non-object" when xml is loaded directly from string response vs from saved response.

//This code works
$response = simplexml_load_file( "response.xml" );
var_dump($response);
echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];

//Returns
//object(SimpleXMLElement)#153 (4) { ["@attributes"]=> array(1)...the rest of the xml file...
//Order_Number

//This code returns error
$response = simplexml_load_string( $response );
var_dump($response);
echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];

//Returns
//object(SimpleXMLElement)#153 (1) { [0]=> string(33864) "" }
//Notice: Trying to get property of non-object in...

What would cause the xml to fail when using simplexml_load_string instead of simplexml_load_file?

Here is a snippet of the xml file:

<?xml version="1.0" encoding="UTF-8"?>
<RESPONSE_GROUP>
    <RESPONSE>
        <RESPONSE_DATA>
            <FILE_INFORMATION Order_Number="19222835">
                ...
            </FILE_INFORMATION>
        </RESPONSE_DATA>
    </RESPONSE>
</RESPONSE_GROUP>

Solution

  • This works for me:

    <?php
    
    $response = '<?xml version="1.0" encoding="UTF-8"?>
    <RESPONSE_GROUP>
        <RESPONSE>
            <RESPONSE_DATA>
                <FILE_INFORMATION Order_Number="19222835">
                    ...
                </FILE_INFORMATION>
            </RESPONSE_DATA>
        </RESPONSE>
    </RESPONSE_GROUP>';
    
    
    //This code returns error
    $response = simplexml_load_string( $response );
    var_dump($response);
    echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];
    
    
    ?>
    

    Output:

    object(SimpleXMLElement)#1 (1) {
      ["RESPONSE"]=>
      object(SimpleXMLElement)#2 (1) {
        ["RESPONSE_DATA"]=>
        object(SimpleXMLElement)#3 (1) {
          ["FILE_INFORMATION"]=>
          string(33) "
                    ...
                "
        }
      }
    }
    19222835