Page 1 of 1

file_get_contents doesn't read file from variable

Posted: Sun Oct 18, 2009 4:00 am
by cartrave
Hi,
I'm facing a really strange problem. I have a file named 'map' with the following contents:
1;'pag1.html'
2;'pag2.html'
3;'pag3.html'

Then I try to read it with the following php code:

Code: Select all

$lines = file('map');
foreach ($lines as $line_num => $line) {
  list($num,$filename)=explode(";",$line);
  if ($num==2) {
    echo file_get_contents($filename);
    break;
  }
}
My expectation was to see the content of the file pag2.html but php says that the file doesn't exist. I tried this by:

Code: Select all

file_exists ($filename)
Much more strange is that if I use the following code:

Code: Select all

echo file_get_contents('pag2.html')
instead of the variable $filename I have no problem to see the file contents.

So why I can see the file pag2.html contents if I use file name string but the file doesn't exist if I use the variable $filename ?

Many thank in advance.

Re: file_get_contents doesn't read file from variable

Posted: Sun Oct 18, 2009 5:34 am
by Mark Baker
Your code to read from the file and explode the $filename results in a value in the $filename variable that actually contains quote marks.... so file_get_contents($filename) is looking for a file on the server filesystem that actually has quote marks in the file name.

Either modify your map file to read:
1;pag1.html
2;pag2.html
3;pag3.html
without the quotes
or strip the quotes from the value of $filename before using file_get_contents($filename)

Code: Select all

 
$filename = trim($filename,"'");
echo file_get_contents($filename);

Re: file_get_contents doesn't read file from variable

Posted: Sun Oct 18, 2009 5:43 am
by social_experiment
In your 'map' file change the
1;'pag1.html'
2;'pag2.html'
3;'pag3.html'
to
pag1.html
pag2.html
pag3.html
then you use the following code :

Code: Select all

 
<?php
 $lines = file('map'); #read entire file into an array
    
  foreach ( $lines as $key => $value ) {
     if ( $key == 2 ) {
      echo file_get_contents($value);
     }
  }
?>
 
If you use the 'foreach' construct for an associative array, it returns the key which you can then test against to decide which file you want to read. I saw the other post while writing this and im not sure if the values ( pag1.html, pag2.html, pag3.html ) wil be located next to each other or each one on a new line within the 'map' file. If that is the case, my example might not work. ( I think )

It's simplistic but hope this helps.