0

May I ask a dumb question? I have already checked the answers for the same error such as. PHP - Failed to open stream : No such file or directory. and couple of others.

However, this one seems more elmentary problem. I am using XAMPP and I have checked the the property of csv file and it says the location. C:\xampp\htdocs Then, I checked http://localhost/Untitled-2.php and it reutrns:

Warning: file(Book 1.csv 1): failed to open stream: No such file or directory in C:\xampp\htdocs\Untitled-2.php on line 2

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\Untitled-2.php on line 3

Why am I getting these error? My code is the following script:

<?php
     $read = file("Book 1.csv 1");
     foreach($read as $line){
         echo $line .",";
        }
?>
kimi Tanaka
  • 119
  • 2
  • 12

2 Answers2

1

I'm assuming your filename is Book 1.csv because it makes more sense. Your code might have a typo, as the file source is currently Book 1.csv 1 and this could be the cause of your problem.

Try this:

$read = file("Book 1.csv");
Niksuski
  • 45
  • 4
1

So, I think you have a problem with relative and absolute paths.

file("foo.bar") will try to open the file foo.bar relative to your current path. If you ran your php script from the command line, it will try to open the file in the directory you were in when you ran php.

So if you have the following directory structure:

/foo/
   /foo/test.php
   /foo/bar.csv
/bar.txt

And you are running php from your root directory:

/ $ php /foo/test.php

The working directory of your file will be /, even though the php file itself was in /foo. So if you do

file('bar.csv');

What php will try to open is in fact /bar.csv which doesn't exist.

Please note that what will be the relative working directory of your script can greatly differ in how your script were ran. If it is running from php-fpm mode, it will depend on your config.

To test what your current working directory is, do

echo getcwd();

And then you can list the contents of your working directory with

$files = glob(getcwd() . DIRECTORY_SEPARATOR, GLOB_NOSORT);
var_dump($files);

Or you could do something similar with readdir

All in all, I think you should try to avoid using relative file paths, as it can open up all sorts of problems. If possible, try to use absolute paths instead, like:

file('/var/www/file.csv');
Xyz
  • 5,955
  • 5
  • 40
  • 58
  • Thanks. Very felpful! Now I am doing echo getcwd() . It says C:\xampp\htdocs Then, $files = glob(getcwd() . DIRECTORY_SEPARATOR, GLOB_NOSORT) It returns var_dump($files); array(1) { [0]=> string(16) "C:\xampp\htdocs\" } I am trying to figure it out from your answer what it is. – kimi Tanaka Oct 22 '17 at 02:10