Search code examples
phpdomxpathdomxpath

GettingAttribute Content with Xpath and 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>

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!


Solution

  • Have you tried DOMElement::getAttribute ?

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