2016-04-20 51 views
1

我想知道是否可以在PHP文件锁中使用simplexml打开,读取和写入xml文件。如果这是不可能的,我怎样才能实现锁定文件,并在同一时间使用简单的XML读取/写入?PHP flock()用Simplexml打开,读写

例如:

$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); 

回答

1

只需使用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。