XML parse error

General discussion on PHP

XML parse error

Postby beanoefc on Sun Feb 12, 2012 12:44 am

Hey Everyone,

I have been given an assignment where i am given an XML file and i need to parse it. The XML is in the following format:
Code: Select all
<?xml version="1.0"?>
<title>Library</title>
<library>
   <book id="1">
      <author>J.K.Rowling</author>
      <name>Harry Potter and the Philosopher's Stone</name>
   </book>
   <book id="2">
      <author>J.K.Rowling</author>
      <name>Harry Potter and the Chamber of Secrets</name>
   </book>
</library>


The problem i have is when i try an parse this XML, with SimpleXML, i get the following error
parser error : Extra content at the end of the document

The source of this error is due to there being no root node.

This has left me in a bit of a predicament. Is there anyway of parsing XML in this format without the root node being added?

Regards,
-Ben
beanoefc
 
Posts: 45
Joined: Wed Jun 23, 2010 9:05 pm

Re: XML parse error

Postby mkherlakian_zend on Mon Feb 13, 2012 4:28 am

Not to my knowledge...
I tried loading it into a DOM fragment first (you have to strip the <?xml version...?> -http://www.php.net/manual/en/domdocumentfragment.appendxml.php), but if you try using simplexml_import_dom() it throws an error...
User avatar
mkherlakian_zend
 
Posts: 88
Joined: Tue Jan 10, 2012 2:41 pm

Re: XML parse error

Postby ericritchie on Mon Feb 13, 2012 11:49 am

Hi Ben,

I would go the brute force approach of loading the file into an array with the file() PHP function, checking if the first line contained the XML declaration (deleting it if so) and then throw a root node around the text and pass it to simple_xml.

Dirty, perhaps, but it will get the job done.

Hope this helps (and does not sicken you too much)...

Regards,
Eric.
User avatar
ericritchie
 
Posts: 118
Joined: Tue Feb 10, 2009 10:09 am


Return to PHP

Who is online

Users browsing this forum: No registered users and 5 guests