Ankur
Ankur

Reputation: 48

Alternately getting the error (Extra content at the end of the document )

I am getting error while loading the xml file. I got many answers related to the topic but I really could not find why this error maybe coming in my file.

Warning: DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Extra content at the end of the document 

When I am running the file, it runs successfully, but when I reload it, it gives the above error instead of adding another node. But, next time when I reload it runs successfully again. This is happening alternatively. Please someone tell me why is this happening and how to solve the problem.

I am using this php code to edit the xml file:

<?php
$dom = new DomDocument("1.0", "UTF-8");
$dom->load('filename.xml');

$noteElem = $dom->createElement('note');
$toElem = $dom->createElement('to', 'Chikck');
$fromElem = $dom->createElement('from', 'ewrw');

$noteElem->appendChild($toElem);
$noteElem->appendChild($fromElem);

$dom->appendChild($noteElem);
$dom->formatOutput = TRUE;
//$xmlString = $dom->saveXML();
//echo $xmlString;
$dom->save('filename.xml');
?>

This is the xml file I am editing:

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Chikck</to>
  <from>ewrw</from>
</note>

Upvotes: 2

Views: 1650

Answers (1)

Dale
Dale

Reputation: 10459

The extra content error is caused by having two of the same node, in this case the note node, as a root element.

You could add a new root element notes for example, and then add more note elements within that.

Here's an example using the simplexml library (just because I use this one and I'm familiar with it)

New filename2.xml: (with added notes element as root)

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
        <to>Chikck</to>
        <from>ewrw</from>
    </note>
</notes>

PHP script:

<?php
    $xml = simplexml_load_file('filename2.xml');
    $note = $xml->addChild('note');
    $to = $note->addchild('to', 'Chikck');
    $from = $note->addChild('from', 'ewrw');
    $xml->asXML('filename2.xml');
?>

filename2.xml after running script:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note>
        <to>Chikck</to>
        <from>ewrw</from>
    </note>
    <note>
        <to>Chikck</to>
        <from>ewrw</from>
    </note>
</notes>

Upvotes: 3

Related Questions