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?

有帮助吗?

解决方案

$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>
 */

其他提示

Either use file locking or make your writes atomic so that other processes don't see half-written files. See the middle of this answer for code for both approaches.

You could also mediate your writes through something that handles the concurrency for you and gives you consistent reads and writes, i.e. a database. It doesn't have to be a full-blown standalone process--you can use sqlite or a simple key-value store.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top