Home >Backend Development >PHP Tutorial >Too simple too naive Instructions for using the simplexml_load_string function in PHP

Too simple too naive Instructions for using the simplexml_load_string function in PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 08:44:091186browse

First use a piece of code to reproduce the problem
At first glance, the result is very confusing:

Copy the code The code is as follows:


$string = <<< ;data>
hello
world

EOF;
$data = simplexml_load_string($string);
print_r($data);
print_r($data->foo);
?>


At first glance, the result is confusing:

Copy Code The code is as follows:


SimpleXMLElement Object
(
[foo] => Array
(
[0] => SimpleXMLElement Object
(
[bar] => hello
)
[1] => ; SimpleXMLElement Object
(
[bar] => world
)
)
)
SimpleXMLElement Object
(
[bar] => hello
)


Obviously print_r shows that foo is an array with two bar elements , but in the end only one bar element is displayed!
The reason is actually very simple. In the result of simplexml_load_string shown above, foo is not an array, but an iterable object!
You can confirm like this:

Copy the code The code is as follows:


foreach ($data->foo as $v) print_r($v);
foreach ($data->children() as $ v) print_r($v);


It seems that the appearance of print_r or var_dump is not completely trustworthy, so please pay more attention to it.

The above introduces the instructions for using the simplexml_load_string function in too simple too naive PHP, including the content of too simple too naive. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn