php 脚本获取一个节点值,如果它等于指定值;更改节点值具有相同的父节点 [英] php scripts gets a node value , if it equals specified value ; changes a node value has its same parent node

查看:60
本文介绍了php 脚本获取一个节点值,如果它等于指定值;更改节点值具有相同的父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

脚本将类似于此

<?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"限制对这个name"节点之后的rate"节点的更改['name']" 值.实施将有很大帮助亲切的问候:)

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 :)

推荐答案

你可以这样做

$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>

这篇关于php 脚本获取一个节点值,如果它等于指定值;更改节点值具有相同的父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆