SimpleXML PHP - 为什么DOM函数不起作用,cdata麻烦

时间:2011-08-01 14:46:54

标签: php simplexml cdata

我一直在尽力在xml中创建cdata条目。我的最新尝试如下。我甚至无法通过我创建新DOMDocument的第一个语句。有什么想法吗?

<?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";
?>

2 个答案:

答案 0 :(得分:1)

在XML声明之前,您不应该有任何字符。删除$xml = '处的换行符。

最好的解决方案是使用heredoc语法:

$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 :(得分: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>