【问题标题】:PHP flock() with Simplexml open, read and writePHPflock() 与 Simplexml 打开、读取和写入
【发布时间】:2016-04-20 21:18:50
【问题描述】:

我想知道是否可以在 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);

【问题讨论】:

    标签: php xml simplexml file-locking flock


    【解决方案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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多