質問

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