Search code examples
phpxmlxmlreaderxmlwriter

Read XML file while its being writen into it PHP


Is there a way to read a XML file even the file is broken?

I'm trying to get an XML file while the file is being written into it and output it, but I'm getting an broken error since the root element is not closed because its in the middle of being written.

Is there anyway how to achieve this?


Solution

  • $broken ='<root>
         <item>foo</item>';
    
    $d  = new DOMDocument();
    $d->loadXML($broken);
    echo $d->saveXML($d); // useless, only prologue
    $d->recover = true; // <--  it's limited, but will try its best.
    $d->loadXML($broken);
    echo $d->saveXML($d);
    /*
     * <?xml version="1.0" encoding="UTF-8"?>
     * <root>
     * <item>foo</item></root>
     */