views:

82

answers:

3

how do i check using php dom, if an xml file exists, and if not create it.

<?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');

?>

right now, since it doesn't exists, it gives me this error:

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

using file_exists('sample.xml')

Mchl
+8  A: 

Don't do that with dom, check it yourself:

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

The saving to file would be done automatically with the $xmldoc->save(); further on.

Wrikken
You might also want to check that the path points to a file (`is_file()`), that the file is readable (if it exists, `is_readable()`) and is writeable (`is_writable()`).
salathe
Wrikken
thank you very much.
fuz3d
A: 

load function returns true and false. Try to use this code:

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

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

netme