Search code examples
phpsimplexml

PHP - simplexml_load_string doesn't work as expected


When converting xml to object, everything seems fine according to print_r($result);. But if I use $result->title it returns object instead of string and when looping $result->documents it gets really strange..

$xml = '<return>
  <id>65510</id>
  <title>SMART</title>
  <info/>
  <documents>
    <name>file_1.pdf</name>
    <path>http://www.domain.com/documents/file_1.pdf</path>
  </documents>
  <documents>
    <name>file_2.pdf</name>
    <path>http://www.domain.com/documents/file_2.pdf</path>
  </documents>
  <documents>
    <name>file_3.pdf</name>
    <path>http://www.domain.com/documents/file_3.pdf</path>
  </documents>
</return>';

$result = simplexml_load_string($xml);
print_r($result);   /* returns:

SimpleXMLElement Object
(
    [id] => 65510
    [title] => SMART
    [info] => SimpleXMLElement Object
        (
        )

    [documents] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [name] => file_1.pdf
                    [path] => http://www.domain.com/documents/file_1.pdf
                )

            [1] => SimpleXMLElement Object
                (
                    [name] => file_2.pdf
                    [path] => http://www.domain.com/documents/file_2.pdf
                )

            [2] => SimpleXMLElement Object
                (
                    [name] => file_3.pdf
                    [path] => http://www.domain.com/documents/file_3.pdf
                )

        )

)
*/
$_VALUE['title'] = $result->title;
print_r($_VALUE);   /* returns:

Array
(
    [title] => SimpleXMLElement Object
        (
            [0] => SMART
        )

)
*/

foreach ($result->documents as $key=>$value) {
echo $key . "<br/>";
}  /* returns:

documents 
documents 
documents 

instead of returning:
1
2
3
*/

I need $result->title to return string and $result->documents to be an array with indexes 1,2,3.


Solution

  • There are difference between print_r and echo in this context. Instead Print try echo

    echo (string) $result->title;
    

    It will work and output as SMART

    and array

    $p = 1;
    foreach ($result->documents as $value) {
      echo $value->name . "<br/>";
      //for key
      echo $p++.'</br>';
    }