Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php xml dom getElementById and DOMXpath query fails getting element

I have some problems making a function to replace question and answer elements in my XML file. I did alot of research learning php dom but I'm running stuck at making this function. The problem is that when I'm trying to get the parent element row by attribute id it returns null or when I use xpath it returns an empty object. I don't know if the function will work correct after I get the the right parent element but that's the next step I think.

my XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row id="1">
    <question>Wat doet de vuilnisman?</question>
    <answer>Hij tilt de vuilnisbak in de vuilnisauto.</answer>
  </row>
  <row id="2">
    <question>Wat zegt de tandarts vaak?</question>
    <answer>U mag nu spoelen.</answer>
  </row>
</root>

and my php function:

//modifies rows
function modifyRows($file, $rowIds, $rowText) {
    $xmlDoc = new DOMDocument();
    $xmlDoc->preserveWhiteSpace = false;
    $xmlDoc->formatOutput = true;   
    $xmlDoc->load($file);
    foreach($rowIds as $rowId) {
        $parent = $xmlDoc->getElementById($rowId);
        for($i=0;$i<count($rowText);$i++) {
            $newQ = $xmlDoc->createElement('question');
            $qText = $xmlDoc->createTextNode($rowText[$i]);
            $qText = $newQ->appendChild($qText);
            $newA = $xmlDoc->createElement('answer');
            $aText = $xmlDoc->createTextNode($rowText[$i++]);
            $aText = $newA->appendChild($aText);
        }
        $oldQ = $parent->getElementsByTagName('question');
        $oldA = $parent->getElementsByTagName('answer');        
        $parent->replaceChild($newQ, $oldQ);
        $parent->replaceChild($newA, $oldA);
    }   
    $xmlDoc->save($file);
}

$rowIds is an array which contains the numbers of the rows that where modified ans rowText in an array which contains the question and answer strings like array(0=>"question",1=>"answer") and so on. The XML file content can get bigger or smaller by adding or removing rows. I have already made "working" functions for that.

like image 844
Zeebats Avatar asked Dec 11 '22 15:12

Zeebats


1 Answers

I have solved the problem thanx to hakre and the internet. So for people with the same problem this is how I solved it.

    function getElementById($id) {
        $xpath = new DOMXPath($this->xmlDoc);
        return $xpath->query("//*[@id='$id']")->item(0);
    }
like image 184
Zeebats Avatar answered Feb 06 '23 01:02

Zeebats