使用 Xpath 和 DOM 获取属性内容 (php)

发布于 2024-10-09 14:14:56 字数 951 浏览 0 评论 0原文

   $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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

像极了他 2024-10-16 14:14:56

您是否尝试过 DOMElement::getAttribute

$id = $question->getAttribute('id');

Have you tried DOMElement::getAttribute ?

$id = $question->getAttribute('id');
若水般的淡然安静女子 2024-10-16 14:14:56

我认为您应该提供 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文