繁体   English   中英

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

[英]check if the file exists, if not, create

我如何检查使用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');

?>

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

DOMDocument::load(): I/O warning : failed to load external entity 

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

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

保存到文件将使用$xmldoc->save();自动完成$xmldoc->save(); 进一步。

使用file_exists('sample.xml')

load函数返回true和false。 尝试使用此代码:

...
$res = $xmldoc->load('sample.xml');
if ($res === FALSE)
{
     /// not exists
}

http://de2.php.net/manual/en/domdocument.load.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM