XML 更改属性所在的值

XML change value where attribute is

使用 PHP 我想更改我指定属性的节点中的值。 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>

例如: 今天是星期一所以 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>

如何在 PHP 中执行此操作?

您可以使用 DOMdocumentDOMpath 更改它只需更改 xml 文件名,data.xml (2x)。设置 $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!"

?>

如果您的文件总是很小且内容相似(如您的示例),您可以 preg_replace() 它们(或者 str_replace())...最好的解决方案是编写您的拥有 XML 解析器,这对所有程序员来说都是一个很好的入门仪式。

http://php.net/manual/en/book.xml.php

我推荐 simpleXML,因为它 - 很好 - 简单:

$xml = simplexml_load_string($x); // assume XML in $x
$id = 1; 

$day = $xml->xpath("*[@id=`$id`]")[0];
$day[0] = 5;

查看结果:

echo $xml->asXML();

评论:

  • xpath-表达式将在$id前select天返回一个SimpleXML-元素数组。
  • select 第一个元素(索引 [0])并将其存储在 $day 中(需要 PHP >= 5.4)

看到它工作:https://eval.in/388827

进一步思考

如果你这样做 XML,通过这样来增加清晰度和灵活性:

<days>
    <day name="Maandag" id="1">0</day>
    <day name="Dinsdag" id="2">0</day>
    <etc />
</days>