illycut
illycut

Reputation: 1

SimpleXML PHP - Why DOM functions don't work, cdata trouble

Ive been trying every way possible to create cdata entries in my xml. My latest attempt is as follows. I can't even get passed for the first statement where im creating a new DOMDocument. Any ideas?

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

Upvotes: 0

Views: 284

Answers (2)

Yoshi
Yoshi

Reputation: 54649

Have a look at: 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();

Output:

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

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237845

You should not have any characters before the XML declaration. Remove the line break at $xml = '.

The neatest solution would be to use heredoc syntax:

$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;

Upvotes: 1

Related Questions