问题
just like the title I need help in a php script gets "name" node value , if it equals specified given value ; changes "rate" node value has its same "person" parent node. the xml file 'rate.xml' like the following
<?xml version="1.0"?>
<user>
<person>
<name>jessy</name>
<rate>2</rate>
</person>
<person>
<name>mice</name>
<rate>5</rate>
</person>
</user>
the script will be similar to this
<?php
$name = $_POST['name'];
$like = $_POST['like'];
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadXML(file_get_contents ('rate.xml'));
$xpath = new DOMXPath($doc);
$nlist = $xpath->query("//user/person/rate");
$node = $nlist->item(0);
$newval = trim($node->nodeValue)-1;
$node->nodeValue = $newval;
file_put_contents ('rate.xml', $doc->saveXML());
?>
My missing part is how to type "if" condition checks if name equals the name I passed to "POST" and how to limit the change to the "rate" node that comes after this "name" node with the "POST['name']" value. implementation will be a great help Kind regards :)
回答1:
You can just do this
$name = "jessy";
$xml = '<?xml version="1.0"?>
<user>
<person>
<name>jessy</name>
<rate>2</rate>
</person>
<person>
<name>mice</name>
<rate>5</rate>
</person>
</user>';
$xml = new SimpleXMLElement($xml);
for($i = 0; $i < count($xml->person); $i ++) {
if ($xml->person[$i]->name == $name) {
$xml->person[$i]->rate = $xml->person[$i]->rate - 1;
}
}
echo $xml->asXML();
Output
<?xml version="1.0"?>
<user>
<person>
<name>jessy</name>
<rate>1</rate> <----- Modified rate for jessy
</person>
<person>
<name>mice</name>
<rate>5</rate>
</person>
</user>
来源:https://stackoverflow.com/questions/12934373/php-scripts-gets-a-node-value-if-it-equals-specified-value-changes-a-node-va