PHP - SimpleXML parse error

前端 未结 4 984
小鲜肉
小鲜肉 2020-12-10 07:21

SEE EDITS AT BOTTOM TO SHOW MORE ACCURATE ERROR OUTPUT

I\'m parsing somewhat large (~15MB) XML files with PHP for the first time using SimpleXML. The files are flig

相关标签:
4条回答
  • 2020-12-10 07:38

    I had this problem with 13MB files and solved it by including LIBXML_PARSEHUGE parameter:

    $xml = new SimpleXMLElement($contents, LIBXML_PARSEHUGE);
    

    NOTE: using ini_setat 1GB didnt solve my problem because PARSED contents occupied more than this.

    A more radical approach is using other libraries to STREAM rather than LOAD WHOLE FILE (SAX parser versus DOM parser), like XML Streamer

    0 讨论(0)
  • 2020-12-10 07:43

    Maybe the parsed xml file may be too big for the parser. But you can try to pass LIBXML_PARSEHUGE as an option - which helped in my case.

    0 讨论(0)
  • 2020-12-10 07:54

    As mentionned in other answers and comments, your source XML is broken and XML parsers are supposed to reject invalid input. libxml has a "recover" mode which would let you load this broken XML, but you would lose the "&sid" part so it wouldn't help.

    If you're lucky and you like taking chances, you can try to somehow make it work by kind-of-fixing the input. You can use some string replacement to escape the ampersands that look like they're in the query part of an URL.

    $xml = file_get_contents('broken.xml');
    // replace '&' followed by a bunch of letters, numbers
    // and underscores and an equal sign with &
    $xml = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xml);
    $sxe = simplexml_load_string($xml);
    

    This is, of course, nothing but a hack and the only good way to fix your situation is to ask your XML provider to fix their generator. Because if it generates broken XML, who knows what other errors slip by unnoticed?

    0 讨论(0)
  • 2020-12-10 07:54

    Darryl has the right answer as to why this is happening in his comment above. One way of fixing this would be to do a str_replace() to replace all '&' ampersands with '&' in the XML. According to the PHP manual you could also use this regular expression to replace ampersands with their entities:

    $s = preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&'.substr('\\0',1))", 
    
    0 讨论(0)
提交回复
热议问题