1

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.

1 Answer 1

1

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>';
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, but I use these values in PHPMailer and it throws error: Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
ok then you have to type case data as string because internally they are all SimpleXMLElement.So it should like echo (string) $result->title;
And what about the array?

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.