How to parse an XML ignoring errors with SimpleXML

后端 未结 1 358
不思量自难忘°
不思量自难忘° 2021-01-16 08:16

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 th

1条回答
  •  太阳男子
    2021-01-16 08:21

    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

    
        Hankre
        2
         16 
        
            Nice 
            Food 
            
    

    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

    
        Hankre
        2
        16
        
            Nice
            Food
            
        
    
    

    0 讨论(0)
提交回复
热议问题