Reputation: 1900
i already search here before i ask this question.. I know there is an answer here somewhere.. but i can't find it..
I want to be able to edit child node by id in my xml file.. i tried alot of script but i'm having a really bad time with this..
please see this line in edit.php:
echo "the problem is in the next line";
this is the last line that the server reads..
thanks you for your help.
events.xml
<?xml version="1.0" encoding="UTF-8" ?>
<events>
<record>
<id>1</id>
<event>a</event>
<eventDate>a</eventDate>
<desc>a</desc>
</record>
<record>
<id>2</id>
<event>b</event>
<eventDate>b</eventDate>
<desc>b</desc>
</record>
</events>
edit.php
header("Content-type: text/html; charset=utf-8");
$record = array(
'id' => $_POST['id'],
'event' => $_POST['event'],
'eventDate' => $_POST['eventDate'],
'desc' => $_POST['desc'],
);
$id = $record["id"];
$dom = new DOMDocument;
$dom->load('events.xml');
$xpath = new DOMXPath($dom);
$query = sprintf('/events/record[./id = "%d"]', $id);
foreach($xpath->query($query) as $record) {
$eventN = $record->parentNode->getElementsByTagName("event");
echo "the problem is in the next line";
$eventN->item(0)->nodeValue = $record["event"];
$dateN = $record->parentNode->getElementsByTagName("eventDate");
$dateN->item(0)->nodeValue = $record["eventDate"];
$descN = $record->parentNode->getElementsByTagName("desc");
$descN->item(0)->nodeValue = $record["desc"];
}
$dom->save("events.xml");
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
Edited: Working edit.php but not dynamic
<?php
header("Content-type: text/html; charset=utf-8");
$record = array(
'id' => $_POST['id'],
'event' => $_POST['event'],
'eventDate' => $_POST['eventDate'],
'desc' => $_POST['desc'],
);
$id = $record["id"];
$dom = new DOMDocument;
$dom->load('events.xml');
$xpath = new DOMXPath($dom);
$query = sprintf('/events/record[./id = "%d"]', $id);
foreach($xpath->query($query) as $record) {
$eventN = $record->parentNode->getElementsByTagName("event");
echo "i change it to string text and it's works. ";
$eventN->item(0)->nodeValue = 'text';
$dateN = $record->parentNode->getElementsByTagName("eventDate");
$dateN->item(0)->nodeValue = 'text';
$descN = $record->parentNode->getElementsByTagName("desc");
$descN->item(0)->nodeValue = 'text';
}
$dom->save("events.xml");
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
Upvotes: 2
Views: 4173
Reputation: 316979
Ok, the issue is your $record
array from the beginning is overwritten in the foreach
.
Either change the as $record
or change the name of the array holding the $_POST
data.
On a sidenote, you are iterating over elements, so there is no reason to get to the parentNode. Use
$record->getElementsByTagName("event");
Upvotes: 6