0

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>
3
  • You (re)load xml file before save it, all your first changes will be ignore Commented Nov 28, 2017 at 10:47
  • @Camille, I'm sorry. I forgot to remove that from my tests, but that's not the problem. Commented Nov 28, 2017 at 10:51
  • There are no date1 and date2 but StartDate and endDate Commented Nov 28, 2017 at 12:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.