在php中根据父节点的属性存储xml子节点的内容
我正在尝试显示从 xml 结果返回的最大图像 url。到目前为止,返回的最大高度是 400 高,所以我硬编码了 400 英寸。如果可能的话,我想只选择最大的,以防将来我得到的结果中没有 400 高度图像。
我试过
$x = file_get_contents($url);
$xml = simplexml_load_string($x);
$imageURL=$xml->categories->category->items->product->images->image[@height='400']->sourceURL;
这给了我“语法错误,意外的'=',期待']'”。
我也尝试过:
$imageURL= $xml->xpath("/categories/category/items/producct/images/image[@height='400']/sourceURL");
但链接不好。 这是 XML:
<images>
<image available="true" height="100" width="100">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="200" width="200">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="300" width="300">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="400" width="400">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="399" width="400">
<sourceURL>
Someurl.com
</sourceURL>
</image>
</images>
有什么想法吗?
I'm trying to display the biggest image url returned from an xml result. So far the largest returned is 400 high so I hardcoded 400 in. If possible I would like to select just the largest in case in the future I get results that don't have a 400 height image in them.
I've tried
$x = file_get_contents($url);
$xml = simplexml_load_string($x);
$imageURL=$xml->categories->category->items->product->images->image[@height='400']->sourceURL;
Which gives me "syntax error, unexpected '=', expecting ']'".
And I also tried:
$imageURL= $xml->xpath("/categories/category/items/producct/images/image[@height='400']/sourceURL");
But got a bad link.
Here is the XML:
<images>
<image available="true" height="100" width="100">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="200" width="200">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="300" width="300">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="400" width="400">
<sourceURL>
Someurl.com
</sourceURL>
</image>
<image available="true" height="399" width="400">
<sourceURL>
Someurl.com
</sourceURL>
</image>
</images>
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
->image[@height='400']
是直接的 PHP 数组引用。这将被解释为抑制define()
常量 (height
) 上的错误 (@
),并尝试通过赋值='400'
。对于您的 xpath 版本,请记住 xpath 查询返回 DOMNodeList,而不是实际的 DOMElement。要从查询结果中获取所需的 URL,您必须遍历节点列表:
->image[@height='400']
is a direct PHP array reference. This'd be interpreted as supressing errors (@
) on adefined()
constant (height
), and trying to set its value via an assignment='400'
.For your xpath version, remember that an xpath query returns a DOMNodeList, not an actual DOMElement. To get the URLs you need from the query results, you have to ierate over the node list: