0

sorry, but i'm a little bit convused... The properties of the simpleXMLElement, created by the simplexml_load_string method, returns always an one-dimensional array with exactly one . It's no matter if i use one, more or no index - it's all the same result... the only exception is echo:

$xml = simplexml_load_string("<main><name>Alfred</name></main>"); echo $xml->name; //-> Alfred print_r($xml2->name); // -> SimpleXMLElement Object ( [0] => Alfred ) print_r($xml2->name[0]); // -> SimpleXMLElement Object ( [0] => Alfred ) print_r($xml2->name[0][0]); // -> SimpleXMLElement Object ( [0] => Alfred ) $arr['name'] = $xml2->name; echo(json_encode($arr)); //-> {"name":{"0":"Alfred"}} 

And if i use the attribute notation, i get null:

$arr['name'] = $xml2['name']; echo(json_encode($arr)); //-> {"name":null} 

But if i use any string method, i get a clear string:

$arr['name'] = $xml2->name.""; echo(json_encode($arr)); //-> {"name":"Alfred"} $arr['name'] = strtolower($xml2->name); echo(json_encode($arr)); //-> {"name":"alfred"} 

So, can me anybody explain this behavior? Should i just use strval() or what's the correct or most beautyfull way to get the property as string?

2
  • 1
    Yes, you should use strval() or (string) cast to get the value of a node. echo or concatenating node with string do casting to string implicitly. Commented Feb 23, 2020 at 16:33
  • Ok, thank you! I was a little bit confused about the null result by attribute notation. Commented Feb 24, 2020 at 18:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.