PHP flock() 与 Simplexml 打开、读取和写入


PHP flock() with Simplexml open, read and write

我想知道是否可以在 PHP 文件锁中使用 simplexml 打开、读取和写入 xml 文件。如果不可能,如何同时使用简单的 xml 实现锁定文件和读取/写入文件?

例如:

$file = fopen('text.xml', 'r+');
flock($file, LOCK_EX);
if (file_exists('test.xml'))
{
    $xml = simplexml_load_file('test.xml');
    //Retrieve xml element, 
    //Save XML element back to test.xml here
    print_r($xml);
}
else
{
    exit('Failed to open test.xml.');
}
flock($file, LOCK_UN);
只需使用

fread 将内容作为字符串获取,然后使用 simplexml_load_string 而不是 simplexml_load_file 进行解析:

$file = fopen('text.xml', 'r+');
flock($file, LOCK_EX);
// Load the data
$data = fread($file, filesize('text.xml'));
$xml = simplexml_load_string($data);
// Modify here
// Save it back
$new_data = $xml->asXML();
ftruncate($file);
rewind($file);
fwrite($file, $new_data);
flock($file, LOCK_UN);
fclose($file);

为简单起见,示例中省略了错误处理;您应该检查$file是否是有效的句柄,以及$xml是否是有效的 SimpleXMLElement。