我如何使用 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();
自动完成。
关于php - 检查文件是否存在,不存在则创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3361995/