2

Often my .xml document contains errors. I would want to parse my document anyway up to errors or try to fix errors automatically. Is that possible?

I have tried this, but it isn't working

  $xml = simplexml_load_file($url, "SimpleXMLElement", array(LIBXML_NOERROR, LIBXML_ERR_NONE));

    if (!$xml) {
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error) {
            echo "\t", $error->message;
        }
    }
1
  • What did you try so far? Your script only outputs the errors. I don't see anything you do to actually fix something here. Commented Oct 18, 2012 at 14:28

1 Answer 1

12

From PHP DOC simplexml_load_file options should be int not array

Replace

$xml = simplexml_load_file($url, "SimpleXMLElement", array(LIBXML_NOERROR, LIBXML_ERR_NONE));
                                                       ^------- You are using array

With

$xml = simplexml_load_file($url, "SimpleXMLElement", LIBXML_NOERROR |  LIBXML_ERR_NONE);

Instead of suppressing this errors you can as well fix the xml with Tidy package.

Example bad.xml

<Family>
    <name>Hankre</name>
    <adults>2</adults>
    <kids > 16 </kids>
    <food>
        <tag>Nice </tag>
        <tag>Food </tag>
        <tag />

Fix XML

$config = array(
    'indent' => true,
    'clean' => true,
    'input-xml'  => true,
    'output-xml' => true,
    'wrap'       => false
    );

$tidy = new Tidy();
$xml = $tidy->repairfile($badXML, $config);
echo $xml;

Output

<Family>
    <name>Hankre</name>
    <adults>2</adults>
    <kids>16</kids>
    <food>
        <tag>Nice</tag>
        <tag>Food</tag>
        <tag />
    </food>
</Family>
Sign up to request clarification or add additional context in comments.

2 Comments

ok, but the XML doesn't be parsed because SimpleXML got errors. I'd want to be parsed at least up to first error. Do you know how to do that?
yes .... that is entirely something different but it can be done .. you want it here or make it a new time so it would benefit others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.