检查文件是否存在,如果不存在,则创建

inp*_*put 2 php xml file domdocument

我如何检查使用php dom,如果存在xml文件,如果没有创建它.

<?php
    header("Location: index.php");

    $xmldoc = new DOMDocument();
    $xmldoc->load('sample.xml');
    $newAct = $_POST['activity'];

    $root = $xmldoc->firstChild;
    $newElement = $xmldoc->createElement('activity');
    $root->appendChild($newElement);
    $newText = $xmldoc->createTextNode($newAct);
    $newElement->appendChild($newText);
    $xmldoc->save('sample.xml');

?>
Run Code Online (Sandbox Code Playgroud)

现在,因为它不存在,它给了我这个错误:

DOMDocument::load(): I/O warning : failed to load external entity 
Run Code Online (Sandbox Code Playgroud)

Wri*_*ken 10

不要用d​​om做,请自己检查:

if(file_exists('sample.xml')){
    $xmldoc->load('sample.xml');
} else {
    $xmldoc->loadXML('<root/>');//or any other rootnode name which strikes your fancy.
}
Run Code Online (Sandbox Code Playgroud)

保存到文件将在$xmldoc->save();下一步自动完成.

  • 您可能还想检查路径是否指向文件(`is_file()`),文件是否可读(如果存在,`is_readable()`)并且可写(`is_writable()`). (2认同)