使用 Xpath 和 DOM 获取属性内容 (php)
$dom->load('2.xml');
$xpath = new DOMXPath($dom);
$questions = $xpath->query("questions/question");
foreach($questions as $question)
{
if ($question->textContent == "")
{
$question->nodeValue = "{$current_time}";
break;
}
}
<questions>
<question id="1">a<question>
<question id="2"><question>
</questions>
上面的代码正在搜索一个名为 Question 的节点,其 nodeValue 为空。它工作完美。但是,我不知道如何获取当前节点的属性值。例如2是我想要得到的值。
我想在这段代码之后立即执行此操作:
$question->nodeValue = "{$current_time}";
这是我的 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<questions>
<question id="1"></question>
<question id="2"></question>
<question id="3"></question>
</questions>
任何人都可以帮助我解决这个问题吗?谢谢!
$dom->load('2.xml');
$xpath = new DOMXPath($dom);
$questions = $xpath->query("questions/question");
foreach($questions as $question)
{
if ($question->textContent == "")
{
$question->nodeValue = "{$current_time}";
break;
}
}
<questions>
<question id="1">a<question>
<question id="2"><question>
</questions>
Above code is searching for a node called question whose nodeValue is empty. It works perfectly. However, I cannot figure out how to get the current node's attribute's value. for instance 2 is the value I want to get.
I want to do this just right after this code:
$question->nodeValue = "{$current_time}";
Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<questions>
<question id="1"></question>
<question id="2"></question>
<question id="3"></question>
</questions>
Can anybody help me with this issue? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过
DOMElement::getAttribute
?Have you tried
DOMElement::getAttribute
?我认为您应该提供 XML 文件的示例摘录,以便我们可以更轻松地找出您的数据是什么以及您想用它做什么。
顺便说一句,您是否尝试过使用 SimpleXML 而不是 DOM - 我认为它要多得多更容易使用。
I think you should give a sample extract of your XML file, so we could more easily find out what is your data and what you want to do with it.
BTW, have you tried using SimpleXML instead of DOM - I think it's a lot more easier to use.