2

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 
4

3 に答える 3

10

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();さらに進むと自動的に行われます。

于 2010-07-29T11:33:27.797 に答える
2

を使用してfile_exists('sample.xml')

于 2010-07-29T11:32:01.823 に答える
0

load関数はtrueとfalseを返します。このコードを使用してみてください:

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

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

于 2010-07-29T11:35:40.240 に答える