I have an XML file named list.xml
in root of my site. I want to load it via simplexml_load_file()
on each page of my site.
I tried the following code in my template file:
if ($level == 1) {
$xml = simplexml_load_file('list.xml');
} else {
$xml = simplexml_load_file('../list.xml');
}
Variable $level = 1 is set on pages at root level. On the rest of the pages, which are all one level deep, $level is not set and the relative path '../list.xml' should be used for those pages.
The site loads correctly when I access root level pages but the pages one level deep return error:
PHP Warning: simplexml_load_file(): I/O warning: failed to load external entity "list.xml"
I have made sure that the relative path is correct. I tried other combinations of above code but I could not figure out what is wrong. The only way it works is to manually set the path in each webpage. But that way, it would be difficult to maintain.
Thanks for your help!!
instead of trying to customize your script depending on the input file, you can write one line that will work regardless of where in the web tree your script happens to live:
$xml = simplexml_load_file($_SERVER['DOCUMENT_ROOT'] . '/list.xml');