Nick Weavers
Nick Weavers

Reputation: 564

Why is DomDocument loadXML not working for me?

I have a really simple testcase an am going cross eyed trying to spot what I'm doing wrong. here's the testcase:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Contact>
    <Name>Foo Bar</Name>
    <Numbers>
        <Number>9876543210</Number>
        <Number>9876543212</Number>
    </Numbers>
    <Address>
        <Premise>11</Premise>
        <Postcode>ZZ99 9ZZ</Postcode>
    </Address>
</Contact>
XML;

$dom = new domDocument( '1.0', 'utf-8' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->recover = true;
libxml_use_internal_errors(true);
$result = $dom->loadXML($xml);
print_r($result);
$errors = libxml_get_errors();
print_r($errors);
$dom->saveXML($xmlContentFormatted);
echo "<pre lang=xml>";
echo $xmlContentFormatted;
echo "</pre><br><br>";  
?>

And the output:

1Array ( )

Upvotes: 0

Views: 3014

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

There are a few errors in your code, using $doc which isn't defined anywhere - should be $dom, also your attempt to output the document using saveXML is invalid. It was trying to use $xmlContentFormatted as a context node for the save - again $xmlContentFormatted isn't defined anywhere - instead you just use the return value of saveXML() as the output...

$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->recover = true;
libxml_use_internal_errors(true);
$dom->loadXML($xml);
echo "<pre lang=xml>";
echo $dom->saveXML();
echo "</pre><br><br>"; 

Upvotes: 2

Related Questions