[英]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
不要用dom做,请自己检查:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.