SimpleXML - 如何使用属性作为选择器?
给定这个 XML:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<project type="residential">
<item>
<description><![CDATA[Node 1 text]]></description>
</item>
<item>
<description><![CDATA[Node 2 text]]></description>
</item>
</project>
</root>
XML;
?>
我想列出所有字段的内容。
这就是我所拥有的。它失败并显示错误“非对象上的成员函数 xpath()”。
// load xml file
include 'xml/portfolio_xml.php';
$portfolio = simplexml_load_string($xml);
foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
echo $item->description;
}
更新
实际上,这个例子确实有效。显然,我需要将示例从应用程序其余部分的上下文中拉出来。
Given this XML:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<project type="residential">
<item>
<description><![CDATA[Node 1 text]]></description>
</item>
<item>
<description><![CDATA[Node 2 text]]></description>
</item>
</project>
</root>
XML;
?>
I would like to list the content of all of the of the fields.
This is what I have. It fails with an error "member function xpath() on a non-object".
// load xml file
include 'xml/portfolio_xml.php';
$portfolio = simplexml_load_string($xml);
foreach ($portfolio->xpath('//project[@type="residential"]/item') as $item) {
echo $item->description;
}
UPDATE
Actually, this example does work. Obviously pulling the sample out of the context of the rest of my application was what I needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要检查
simple_xml_load_string
是否成功。它现在失败了,因为$portfolio
不是一个对象。这就是为什么我更喜欢使用真正的构造函数而不是函数的部分原因。我更喜欢以这种方式捕获异常并处理错误:
这种方式不仅可以处理错误,还可以根据异常类型、代码、消息或上述所有内容采取特定操作。
此外,根据错误的类型,您可能希望将它们保留在 libxml 内部。
You need to check that
simple_xml_load_string
succeeded. Its failing right now because$portfolio
isnt an object.This is partially why i prefer using the real constructor instead of the function. I prefer to catch exceptions and handle errors that way:
This way not only can you handle the error but you can take specific action based on the Exception type, code, message, or all of the above.
Additionally, depending on the type of errors you may want to keep them internal to libxml.