php - 检查文件是否存在,不存在则创建

标签 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');

?>

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

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/

相关文章:

php - ConstraintViolationListInterface 到 Symfony 中的异常

java - 使用mybatis将多个表映射到一个集合

java - 嵌套类与单独的类文件

java - XML 阅读器错误 : unexpected character content exception while invoking webservice

macos - Grep 文件搜索返回 : Is a directory in OSX Mountain Lion

php - 如何在 php 中上传名称为 utf-8 的文件?

php - 如何从具有特定类的div中删除样式标签

php - 获取运行 PHP include 的文件的文件名

php - 使用 PHP 删除 Linux 服务器上文件夹中的所有文件

xml - 如何更改magento布局xml中<操作方法="addLinkBlock” …>的顺序?