2011-08-01 70 views
0

我一直想盡一切辦法在我的xml中創建cdata條目。我最近的嘗試如下。我甚至無法通過第一條語句創建一個新的DOMDocument。有任何想法嗎?SimpleXML PHP - 爲什麼DOM功能不起作用,cdata麻煩

<?php 
$xml = ' 
<?xml version="1.0" encoding="ISO-8859-1"?> 
<cars> 
    <make name="Ford"> 
     <model>Mustang</model> 
    </make> 
    <make name="Honda"> 
     <model>Accord</model> 
    </make> 
</cars> 
'; 

$dom = new DOMDocument; 

$dom->loadXML($xml); 


$xml = simplexml_import_dom($dom); 
print "working"; 
?> 

回答

1

在XML聲明之前,您不應該有任何字符。刪除$xml = '處的換行符。

最巧妙的解決辦法是使用定界符:

$xml = <<<XML 
<?xml version="1.0" encoding="ISO-8859-1"?> 
<cars> 
    <make name="Ford"> 
     <model>Mustang</model> 
    </make> 
    <make name="Honda"> 
     <model>Accord</model> 
    </make> 
</cars> 
XML; 
1

看一看:DOMDocument::createCDATASection

$xml = '<?xml version="1.0" encoding="ISO-8859-1"?> 
<cars> 
    <make name="Ford"> 
     <model>Mustang</model> 
    </make> 
    <make name="Honda"> 
     <model>Accord</model> 
    </make> 
</cars> 
'; 

$dom = new DOMDocument; 
$dom->loadXML($xml); 

$cdataNode = $dom->createCDATASection('<&>'); 
$dom->documentElement->appendChild($cdataNode); 

echo $dom->saveXml(); 

輸出:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<cars> 
    <make name="Ford"> 
     <model>Mustang</model> 
    </make> 
    <make name="Honda"> 
     <model>Accord</model> 
    </make> 
<![CDATA[<&>]]></cars>