Qas*_*sim 8 php arrays object simplexml
这是我的代码:
$string = <<<XML
<?xml version='1.0'?>
<test>
<testing>
<lol>hello</lol>
<lol>there</lol>
</testing>
</test>
XML;
$xml = simplexml_load_string($string);
echo "All of the XML:\n";
print_r $xml;
echo "\n\nJust the 'lol' array:";
print_r $xml->testing->lol;
Run Code Online (Sandbox Code Playgroud)
输出:
All of the XML:
SimpleXMLElement Object
(
[testing] => SimpleXMLElement Object
(
[lol] => Array
(
[0] => hello
[1] => there
)
)
)
Just the 'lol' array:
SimpleXMLElement Object
(
[0] => hello
)
Run Code Online (Sandbox Code Playgroud)
为什么它只输出[0]而不是整个数组?我不懂.
@Yottatron的建议是正确的,但并非所有情况都如此,例如:
如果你的XML是这样的:
<?xml version='1.0'?>
<testing>
<lol>
<lolelem>Lol1</lolelem>
<lolelem>Lol2</lolelem>
<notlol>NotLol1</lolelem>
<notlol>NotLol1</lolelem>
</lol>
</testing>
Run Code Online (Sandbox Code Playgroud)
Simplexml的输出将是:
SimpleXMLElement Object
(
[lol] => SimpleXMLElement Object
(
[lolelem] => Array
(
[0] => Lol1
[1] => Lol2
)
[notlol] => Array
(
[0] => NotLol1
[1] => NotLol1
)
)
)
Run Code Online (Sandbox Code Playgroud)
并通过写作
$xml->lol->lolelem
Run Code Online (Sandbox Code Playgroud)
你期望你的结果
Array
(
[0] => Lol1
[1] => Lol2
)
Run Code Online (Sandbox Code Playgroud)
但不是,你会得到:
SimpleXMLElement Object
(
[0] => Lol1
)
Run Code Online (Sandbox Code Playgroud)
并通过
$xml->lol->children()
Run Code Online (Sandbox Code Playgroud)
你会得到:
SimpleXMLElement Object
(
[lolelem] => Array
(
[0] => Lol1
[1] => Lol2
)
[notlol] => Array
(
[0] => NotLol1
[1] => NotLol1
)
)
Run Code Online (Sandbox Code Playgroud)
如果你只想要lolelem,你需要做什么:
$xml->xpath("//lol/lolelem")
Run Code Online (Sandbox Code Playgroud)
这给出了这个结果(不是预期的形状,但包含正确的元素)
Array
(
[0] => SimpleXMLElement Object
(
[0] => Lol1
)
[1] => SimpleXMLElement Object
(
[0] => Lol2
)
)
Run Code Online (Sandbox Code Playgroud)
这是因为你有两个lol元素.要访问第二个,您需要这样做:
$xml->testing->lol[1];
Run Code Online (Sandbox Code Playgroud)
这会给你"那里"
$xml->testing->lol[0];
Run Code Online (Sandbox Code Playgroud)
会给你"你好"
SimpleXMLElement的children()方法将为您提供一个包含元素的所有子元素的对象,例如:
$xml->testing->children();
Run Code Online (Sandbox Code Playgroud)
将为您提供一个包含"testing"SimpleXMLElement的所有子项的对象.
如果需要迭代,可以使用以下代码:
foreach($xml->testing->children() as $ele)
{
var_dump($ele);
}
Run Code Online (Sandbox Code Playgroud)
这里有关于SimpleXMLElement的更多信息:
http://www.php.net/manual/en/class.simplexmlelement.php