PHP flock()与Simplexml一起打开、读取和写入
我想知道是否可以在PHP文件锁中使用simplexml打开、读取和写入xml文件。如果不可能,我如何实现锁定文件并同时使用简单xml读/写文件 例如:PHP flock()与Simplexml一起打开、读取和写入,php,xml,simplexml,file-locking,flock,Php,Xml,Simplexml,File Locking,Flock,我想知道是否可以在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 X
$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\u load\u string
而不是simplexml\u load\u 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