[英]XML change value where attribute is
With PHP I want to change the value in the node where attribute is something I specify. 使用PHP,我想更改节点中我指定的属性值。 The XML file:
XML文件:
<?xml version='1.0' standalone='yes'?> <days> <Maandag id="1">0</Maandag> <Dinsdag id="2">0</Dinsdag> <Woensdag id="3">0</Woensdag> <Donderdag id="4">0</Donderdag> <Vrijdag id="5">0</Vrijdag> <Zaterdag id="6">0</Zaterdag> <Zonday id="0">0</Zonday> </days>
For example: Today is Monday so jddayofweek(0) = 1 Then the value of the node with id=1 needs to change, so in the end we get: 例如:今天是星期一,因此jddayofweek(0)= 1然后需要更改id = 1的节点的值,因此最终得到:
<?xml version='1.0' standalone='yes'?> <days> <Maandag id="1">3</Maandag> <Dinsdag id="2">0</Dinsdag> <Woensdag id="3">0</Woensdag> <Donderdag id="4">0</Donderdag> <Vrijdag id="5">0</Vrijdag> <Zaterdag id="6">0</Zaterdag> <Zonday id="0">0</Zonday> </days>
How do I do this in PHP? 如何在PHP中做到这一点?
You could change it using DOMdocument
and DOMpath
Just change the xml filename, data.xml
(2x). 您可以使用
DOMdocument
和DOMpath
更改。只需更改xml文件名data.xml
(2x)。 Set $select
and $changeTo
. 设置
$select
和$changeTo
。
<?php
//Set your variables
$select = 1; //id you'd like to change
$changeTo = 3; //value you would like to change to
//Creating a new DOMDocument
$xmlDoc = new DOMDocument();
//from file
$xmlDoc->load("data.xml");
//Creating a new DOMPath
$Xpath = new DOMXPath($xmlDoc);
//the query selects all Matches any element node (*) that have a "id" attribute with a value of $select
$results = $Xpath->query('*[@id=' . $select . ']');
//Change node
$results->item(0)->nodeValue = $changeTo;
//Save document
$xmlDoc->save("data.xml");
echo "Edited document saved!"
?>
I'd recommend simpleXML
, because it is - well - simple : 我建议使用
simpleXML
,因为它非常简单 :
$xml = simplexml_load_string($x); // assume XML in $x
$id = 1;
$day = $xml->xpath("*[@id=`$id`]")[0];
$day[0] = 5;
see the result: 查看结果:
echo $xml->asXML();
Comments: 评论:
xpath
-expression will select the day by $id
and give back an array of SimpleXML
-elements. xpath
-expression将通过$id
选择日期,并返回一个SimpleXML
-elements数组。 [0]
) and store it in $day
(requires PHP >= 5.4) [0]
)并将其存储在$day
(需要PHP> = 5.4) see it working: https://eval.in/388827 看到它正常工作: https : //eval.in/388827
Thinking further 进一步思考
If you make that XML, add clarity and flexibility by making it like this: 如果您制作该XML,请通过以下方式使其更加清晰和灵活:
<days>
<day name="Maandag" id="1">0</day>
<day name="Dinsdag" id="2">0</day>
<etc />
</days>
If your files are always small and similar content (like your example) you could preg_replace() them (or maybe str_replace())...the best solution is to write your own XML parser, which is a good rite-of-passage for all programmers. 如果文件总是很小且内容相似(例如您的示例),则可以preg_replace()(或str_replace())...最好的解决方案是编写自己的XML解析器,这是一个很好的传递途径适用于所有程序员。
http://php.net/manual/en/book.xml.php http://php.net/manual/en/book.xml.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.