2010-11-05 67 views
2
编辑XML文件

我使用此代码编辑XML文件与CDATA

$xml = simplexml_load_file($xmlfile) or die ("Unable to load XML file!"); 
$event->title = $newtitle; 
$event->description = $newdescription; 
file_put_contents($xmlfile, $xml->asXML()); 

我想添加一个CDATA在description.I使用该代码

$event->description = '<![CDATA['.$newdescription.']]>'; 

但在XML中的<>转换为&lt;&gt;。如何保留CDATA原样。是否有其他编辑方法。提前感谢。

其实我想编辑这个XML文件

<events date="06-11-2010"> 
    <event id="8"> 
     <title>Proin porttitor sollicitudin augue</title> 
     <description><![CDATA[Lorem nunc.]]></description> 
    </event> 
    </events> 
    <events date="16-11-2010"> 
    <event id="4"> 
     <title>uis aliquam dapibus</title> 
     <description><![CDATA[consequat vel, pulvinar.</createCDATASection></description> 
    </event> 
    <event id="1"><title>You can use HTML and CSS</title> 
    <description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events> 

ID为

回答

3

我认为你需要使用DOM当你的需求比较复杂时不再简单。有一种方法createCDATASection

这里有一个基本的例子:

$dom=new DOMDocument(); 
$xml='data.xml'; 
$dom->load($xml); 
$cdata=$dom->createCDATASection('<p>Foo</p>'); 
foreach ($dom->getElementsByTagName('item') as $item) { 
    $item->getElementsByTagName('content')->item(0)->appendChild($cdata); 
} 

$dom->save($xml); 

的XML与此云:

<?xml version="1.0" encoding="utf-8"?> 
<data> 
    <item> 
     <title>Test</title> 
     <content><![CDATA[<p>Foo</p>]]></content> 
    </item> 
</data> 

至于你的榜样和评论,下面应该可以帮助您:

$dom=new DOMDocument(); 
$dom->validateOnParse = true; 

$xml='data.xml'; 
$dom->load($xml); 

// Unless the ID attribute is recognised 
foreach ($dom->getElementsByTagName('event') as $event) { 
    $event->setIdAttribute('id', true); 
} 

$event = $dom->getElementById("1"); 
foreach ($event->getElementsByTagName('description') as $description) { 
    $cdata=$dom->createCDATASection('<p>'. $description->nodeValue .'</p>'); 
    $description->replaceChild($cdata, $description->childNodes->item(0)); 
} 

$dom->save($xml); 
+0

谢谢Cez.I编辑我的问题。我想编辑与相应的id的内容。你可以告诉它是怎么回事? – Warrior 2010-11-05 10:11:29

+0

@THOmas:我已经添加了一个基于XML的示例。希望它应该指向正确的方向 – Cez 2010-11-05 11:05:04

+0

是他们的任何方式来链接xpath和xquery或dom_import_simplexml – Warrior 2010-11-05 11:41:35

-2

尝试

$xml = simplexml_load_file($xmlfile,'SimpleXMLElement', LIBXML_NOCDATA); 

+3

-1你试过吗?它不会解决问题 – Cez 2010-11-05 09:22:42

2

实质上,SimpleXML将转义XML使用的所有值,因此很多使用的原因节点不在那里。如果你确实需要他们,但不能在SimpleXML,使用另一个替代品,如DOMDocument,它的功能createCDATASection()

+0

+1你打败了我,虽然我得到的链接:) – Cez 2010-11-05 09:23:50

+0

呃,尽管你有2个链接,而不是我1,你几秒钟早些时候我相信... – Wrikken 2010-11-05 09:26:55

+0

@Wrikken:睡眠不足意味着我不能说出时间。我厌倦了吗? – Cez 2010-11-05 09:32:39