Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix malformed XML in PHP before processing using DOMDocument functions

I'm needing to load an XML document into PHP that comes from an external source. The XML does not declare it's encoding and contains illegal characters like &. If I try to load the XML document directly in the browser I get errors like "An invalid character was found in text content" also when loading the file in PHP I get lots of warnings like: xmlParseEntityRef: no name in Entity and Input is not proper UTF-8, indicate encoding ! Bytes: 0x9C 0x31 0x21 0x3C.

It's clear that the XML is not well formed and contains illegal characters that should be converted to XML entities.

This is because the XML feed is made up of data supplied by lots of other users and clearly it's not being validated or reformatted before I get it.

I've spoken to the supplier of the XML feed and they say they are trying to get the content providers to sort it out, but this seems silly as they should be validating the input first.

I basically need to fix the XML correcting any encoding errors and converting any illegal chars to XML entities so that the XML loads problem when using PHP's DOMDocument functions.

My code currently looks like:

  $feedURL = '3704017_14022010_050004.xml';
  $dom = new DOMDocument();
  $dom->load($feedURL);

Example XML file showing encoding issue (click to download): feed.xml

Example XML that contains chars that have not been converted to XML entities:

<?xml version="1.0"?>
<feed>
<RECORD>
<ID>117387</ID>
<ADVERTISERNAME>Test</ADVERTISERNAME>
<AID>10544740</AID>
<NAME>This & This</NAME>
<DESCRIPTION>For one day only this is > than this.</DESCRIPTION>
</RECORD>
</feed>
like image 540
Camsoft Avatar asked Feb 14 '10 15:02

Camsoft


1 Answers

To solve this issue, set the DomDocument recover property to TRUE before loading XML Document

$dom->recover = TRUE;

Try this code:

$feedURL = '3704017_14022010_050004.xml';
$dom = new DOMDocument();
$dom->recover = TRUE;
$dom->load($feedURL);
like image 170
AbhiG Avatar answered Sep 21 '22 08:09

AbhiG