簡體   English   中英

XML更改值,其中attribute是

[英]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!"

?>

我建議使用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 -expression將通過$id選擇日期,並返回一個SimpleXML -elements數組。
  • 選擇第一個元素(索引[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>

如果文件總是很小且內容相似(例如您的示例),則可以preg_replace()(或str_replace())...最好的解決方案是編寫自己的XML解析器,這是一個很好的傳遞途徑適用於所有程序員。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM