Dani
Dani

Reputation: 364

DOMDocument not updating nodeValue

So I wrote a piece of code which is supposed to be editing the xml file. But it doesn't seem to work. I have checked everything and all data seems to come through, but somehow it does not update the nodes. Creating the xml file and the data works, adding data works too. But somehow I can't seem to update it.

if ($edit && isset($_POST["submit"])) {
    $doc = new DomDocument('1.0');

    $doc->validateOnParse = true;
    $doc->load('data.xml');        
    $message = getElementById($_GET["id"], $doc);
    $message->getElementsByTagName("title")->nodeValue = 'hey';
    $message->getElementsByTagName("content")->nodeValue = $_POST["content"];
    $target = $message->getElementsByTagName("target")->nodeValue = $_POST["target"];
    $date1 = $message->getElementsByTagName("startDate")->nodeValue = $_POST["date1"];
    $date2 = $message->getElementsByTagName("endDate")->nodeValue = $_POST["date2"];

    $doc->formatOutput = true;
    $doc->save('data.xml');

}

function getElementById($id, $doc)
{
    $xpath = new DOMXPath($doc);
    return $xpath->query("//*[@id='$id']")->item(0);
}

XML:

<message id="5a1c301ae5429" top="12px" left="12px" duration="20">
<title>hey</title>
<content>12345</content>
<target>2</target>
<startDate>27/11/2017 16:30</startDate>
<endDate>27/11/2017 16:50</endDate>
<media type="image" width="200px" height="200px" top="-20px" left="129px">
<uri>
localhost/xml/uploads/4215c27edf5ff51aee0def29f84949be.jpg
</uri>
</media>
</message>

Upvotes: 0

Views: 350

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

When you call getElementsByTagName, this returns a list of nodes that match the tag name. So each time you access the value, you should use...

$message->getElementsByTagName("title")->item(0)->nodeValue = 'hey';

As you only have 1 of each tag, I've used ->item(0) to fetch the first node in the list.

Repeat the same logic for all times you need to access the elements.

Upvotes: 1

Related Questions