lheezy
lheezy

Reputation: 542

Loading a malformed XML in PHP

I have an XML doc that I need to load with PHP. I am currently using the simplexml_load_file() function, however the xml file is malformed, and consequently I am getting a parse error.

The XML file looks something like this:

...
</result>something1>
</else>
</else>
</resu
...

As you can see, this XML is whack and this function is throwing an error trying to parse it. Also I don't need this data that is corrupted. I would just like to read in the stuff that I can and throw everything else away.

Upvotes: 3

Views: 1508

Answers (3)

Zoltan Lengyel
Zoltan Lengyel

Reputation: 360

try to tidy it up, it worked well for me.

http://hu2.php.net/manual/en/intro.tidy.php

Upvotes: 0

Thusjanthan Kuben
Thusjanthan Kuben

Reputation: 51

@Juliusz

You don't actually need to set the strictErrorChecking for this I don't think. I tried the following and it seems to work fine. To ignore the errors you need to set the libxml_use_internal_errors(true). Essentially you want to use DOMDocument instead of simplexml. I tried the following and worked without any problems:

<?php

$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>

</else>
</else>
</document>
XML;

$dom = new DOMDocument();
libxml_use_internal_errors(true); 
$dom->loadHTML($string);
print $dom->saveHTML();


?>

Thusjanthan Kubendranathan

Upvotes: 1

Juliusz Gonera
Juliusz Gonera

Reputation: 4958

As Jonah Bron suggested, try DOMDocument::loadHTML():

$dom = new DOMDocument();
$dom->strictErrorChecking = false;
libxml_use_internal_errors(true);

$dom->loadHTML($xml);

Upvotes: 2

Related Questions