Changing XML node value
This script should change the TOP value of the specified COMMUNITY node. But it doesn't what could be wrong?
<?php
function make_update( $nodeid, $name, $top, $left, $width, $height ) {
$nodes = new SimpleXMLElement('communities.xml', null, true);
$node = $nodes->xpath("//COMMUNITY[@ID='$nodeid']");
$node->TOP->nodeValue = $top;
$nodes->asXML();
return $top;
}
echo make_update(trim($_REQUEST['nodeid']),trim($_REQUEST['name']),trim($_REQUEST['top']),trim($_REQUEST['left']),trim($_REQUEST
['width']),trim($_REQUEST['height']));
?>
The XML looks like this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<COMMUNITIES>
<COMMUNITY ID="c001">
<NAME>Town Services</NAME>
<TOP>50</TOP>
<LEFT>50</LEFT>
<WIDTH>200</WIDTH>
<HEIGHT>300</HEIGHT>
<URLS>
<URL ID="U001">
<NAME>Google.com</NAME>
<URLC>http://www.google.com</URLC>
</URL>
<URL ID="U002">
<NAME>Bing.com</NAME>
<URLC>http://www.bing.com</URLC>
</URL>
<URL ID="U003">
<NAME>Yahoo.com</NAME>
<URLC>http://www.yahoo.com</URLC>
</URL>
开发者_开发问答<URL ID="U004">
<NAME>Aol.com</NAME>
<URLC>http://www.aol.com</URLC>
</URL>
</URLS>
</COMMUNITY>
</COMMUNITIES>
First, you should adjust the code that gets the desired COMMUNITY
element. The xpath
method returns an array of SimpleXMLElement
objects, representing the elements that matched your search string.
Example:
$returnArray = $nodes->xpath("//COMMUNITY[@ID='$nodeid']");
$node = $returnArray[0];
Second, to modify the value of the TOP
element, set directly to TOP
itself:
// This replaces the contents of the TOP element with $top
$node->TOP = $top;
// This appends '<nodeValue>$top</nodeValue>' to the contents of TOP
$node->TOP->nodeValue = $top;
精彩评论