Saif Hamed
Saif Hamed

Reputation: 1094

php: path with include issue. can't reach file from two pages

I'm trying to reach file like this:

index.php
php/page.php
xml/file.xml

index.php:<? include 'php/page.php'; ?>
page.php: <? $xml = simplexml_load_file("xml/file.xml"); ?>

this works fine if i open index.php. but if I open page.php, error will shown. "can't find file php/xml/file.xml "

I know I can use ../ but it will works fine in page.php not in index.php
any idea how i can fix it? (make it works fine from both pages)
Thanx
Regards

Upvotes: 1

Views: 182

Answers (2)

Scott Helme
Scott Helme

Reputation: 4799

I wasn't aware that <? include 'page.php'; ?> should work in index.php as the file is in a folder below.

If that is the case it seems the include function may check child directories if it fails to find the file. Assuming that's the case, page.php will not be able to find file.xml as it is not below it in the tree but is in fact a sibling. The function cannot start randomly traversing your file structure as it may find and include a different file by the same name which you did not intend.

Edit

Updated code makes more sense. Your includes are looking for folders within the current folder. <? $xml = simplexml_load_file("xml/file.xml"); ?> is looking for a folder called xml in the folder php because that is where it is being called from. What you need is <? $xml = simplexml_load_file("/xml/file.xml"); ?> which looks for a folder called xml in the root, notice the addition of the /.

Upvotes: 1

ziollek
ziollek

Reputation: 1993

The easiest way to eliminate that problem is use relative path from point where xml is included. So in page.php paste:

$xml = simplexml_load_file(__DIR__.'/../xml/file.xml');

Upvotes: 1

Related Questions