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?

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • 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. – u_mulder Feb 23 '20 at 16:33
  • Ok, thank you! I was a little bit confused about the null result by attribute notation. – Questioner Feb 24 '20 at 18:00

0 Answers0