2010-09-02 202 views
3

我有一個XML文件添加子節點

<?xml version="1.0" encoding="UTF-8"?> 
<xml> 
<settings> 
<title>Calendar2</title> 
<subTitle>Calendar2</subTitle> 
</settings> 
<events date="02-09-2010"> 
<event> 
<title>HTML Tags</title> 
<description>HTML Tags</description> 
</event> 
</events> 
</xml> 

我怎麼能相對於裏面添加事件標記另一個事件至今

<?xml version="1.0" encoding="UTF-8"?> 
    <xml> 
    <settings> 
    <title>Calendar2</title> 
    <subTitle>Calendar2</subTitle> 
    </settings> 
    <events date="02-09-2010"> 
    <event> 
    <title>HTML Tags</title> 
    <description>HTML Tags</description> 
    </event> 
    <event> 
    <title>Another Title</title> 
    <description>Another description</description> 
    </event> 
    </events> 
    </xml> 

我用這個代碼

$xml_str = file_get_contents($xmlfile); 
$xml = new SimpleXMLElement($xml_str); 
$event = $xml->events->addChild('event'); 
$event->addChild('title', 'More Parser Stories'); 
$event->addChild('description', 'This is all about the people who make it work.'); 
file_put_contents($xmlfile, $xml->asXML()); 

但它會添加到第一個節點。如何添加到事件標記日期02-09-2010

+0

這似乎和你以前的問題一樣:[編輯xml文件](http://stackoverflow.com/questions/3623993/editing-xml-file)。您應該編輯並更新原始問題,而不是創建一個新問題。 – 2010-09-02 07:02:08

回答

1

你要查詢的希望<events>標籤,而不是採取的第一個(這是什麼$xml->events只會返回),使用xpath查詢XML文檔在這裏是有幫助的:

php腳本:

<?php 
$xml_str = file_get_contents('xmlfile'); 
$xml = new SimpleXMLElement($xml_str); 
$wantedEventsTag = $xml->xpath('/xml/events[@date="02-09-2010"]'); 
$wantedEventsTag = $wantedEventsTag [0];//since above fun will return an array 
$wantedEventsTag['attrname']='attrval';//Here's how to add an attribute 
$event = $wantedEventsTag->addChild('event'); 
$event->addChild('title', 'More Parser Stories'); 
$event->addChild('description', 'This is all about the people who make it work.'); 
file_put_contents('xmlfile.xml', $xml->asXML()); 

<events>標籤示例XML文件:

<?xml version="1.0" encoding="UTF-8"?> 
<xml> 
    <settings> 
    <title>Calendar2</title> 
    <subTitle>Calendar2</subTitle> 
    </settings> 
    <events date="01-01-1999"> 
    </events> 
    <events> 
    </events> 
    <events date="02-09-2010"> 
    <event> 
     <title>HTML Tags</title> 
     <description>HTML Tags</description> 
    </event> 
    <event> 
     <title>Another Title</title> 
     <description>Another description</description> 
    </event> 
    </events> 
</xml> 

腳本xpath將匹配所需的節點,我們將在後面使用和添加事件的子節點。

+0

謝謝aularon。它工作正常 – Warrior 2010-09-02 07:11:26

+0

歡迎您:) – aularon 2010-09-02 07:13:05

+0

如何我可以添加一個屬性到事件標記 – Warrior 2010-09-02 07:45:34