我试图在运行PHP 5.3的旧服务器上使用simplexml_load_string解析xml。 xml中的一个标签是并且有几个具有url属性的嵌套子节点。如果我var_dump SimpleXMLElement,images只是一个字符串数组(每个标记的文本节点子节点),没有url属性的标志。
有关为什么没有捕获标签上的url属性的任何想法?
我已经尝试将图片标记上的url属性缩短为大约15个字符,但它们仍未被捕获。
我已经尝试将属性作为图像元素的数组元素以及通过调用image元素上的attributes()方法来访问。
示例XML
<properties xmlns:xs="http://www.w3.org/2001/XMLSchema">
<property>
<reference>####</reference>
...
<images>
<image url="https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_JUxtL~PunupG3r34QY7hcc7wMtgouw9c1H6DUbVNANjxM_Zg--.jpg">A2970_10776141.jpg</image>
<image url="https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_AwVzHs_Ajc3bPh6tAooCEbZkq_ZYbRT5eAjUXsq3Znh_f~Vw--.jpg">A2970_10776142.jpg</image>
...
<links/>
</property>
<property>
...
</property>
</properties>
我的守则
$feed = file_get_contents('test.xml');
$properties = simplexml_load_string($feed);
foreach ($properties as $property) {
var_dump($property->images);
exit;
}
结果
object(SimpleXMLElement)#5 (1) {
["image"]=>
array(19) {
[0]=>
string(18) "A2970_10776141.jpg"
[1]=>
string(18) "A2970_10776142.jpg"
...
}
}
我也尝试过:
foreach ($property->images as $image)
{
var_dump($image['url']);
var_dump($image->attributes());
}
$ image ['url']输出NULL
$ image-> attributes()输出有关在非对象上调用attributes()的错误
理想情况下,var_dumping $ property-> images会产生:
object(SimpleXMLElement)#5 (1) {
["image"]=>
array(19) {
[0]=>
object(SimpleXMLElement)#6 (1) {
["@attributes"]=>
array(1) {
["url"]=>
string(162) "https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_JUxtL~PunupG3r34QY7hcc7wMtgouw9c1H6DUbVNANjxM_Zg--.jpg"
}
}
[text]=> "A2970_10776141.jpg"
}
...
}
}
我忘了我多么讨厌SimpleXML。这对我有用:
<?php
$feed = file_get_contents('test.xml');
$properties = simplexml_load_string($feed);
foreach ($properties as $property)
{
foreach($property->images[0] as $image)
{
print($image['url'] . "\n");
}
}
你没有为foreach循环使用正确的值,你应该使用$property->images->image
,因为它是你要迭代的那些元素。之后,您可以选择方法来访问url
属性:
$properties = simplexml_load_string($feed);
foreach ($properties as $property) {
foreach ($property->images->image as $image) {
echo $image['url'] . PHP_EOL;
echo $image->attributes()['url'] . PHP_EOL;
}
}
输出:
https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_JUxtL~PunupG3r34QY7hcc7wMtgouw9c1H6DUbVNANjxM_Zg--.jpg
https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_JUxtL~PunupG3r34QY7hcc7wMtgouw9c1H6DUbVNANjxM_Zg--.jpg
https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_AwVzHs_Ajc3bPh6tAooCEbZkq_ZYbRT5eAjUXsq3Znh_f~Vw--.jpg
https://#####.#########.###/imgV1/QGcM5YXB7ITu20usXVas9zwwpfszaQl0S7VJWTlCweLw8h1OJgGrQ8SrQZiKyUwAW5EgBoJga_AwVzHs_Ajc3bPh6tAooCEbZkq_ZYbRT5eAjUXsq3Znh_f~Vw--.jpg