1

就像我在 php 脚本中需要帮助的标题一样,如果它等于指定的给定值,则获取“名称”节点值;更改“率”节点值具有相同的“人”父节点。xml 文件“rate.xml”如下

<?xml version="1.0"?>
<user>
<person>
<name>jessy</name> 
<rate>2</rate>
</person>
<person>
<name>mice</name>
<rate>5</rate>
</person>
</user>

脚本将与此类似

<?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());


?>

我缺少的部分是如何键入“if”条件检查名称是否等于我传递给“POST”的名称,以及如何使用“POST ['名称”将更改限制在此“名称”节点之后的“速率”节点']“ 价值。实施将是一个很大的帮助亲切的问候:)

4

1 回答 1

1

你可以这样做

$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();

输出

<?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>
于 2012-10-17T12:45:56.487 回答