Reputation: 294
I currently am trying to read an input file that looks like this:
annie Tuesday October 7 at 08:32 pm 1 Cappuccino 2.5
It is delimited by tabs. I am trying to read from this file, called orders.txt, and place this is an associative array $array. This is the code I have so far. I have tried several different versions, but no dice.
function read_file() {
$file = "orders.txt";
$array = array();
if(file_exists($file)) {
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
foreach($lines as $line) {
$splode = explode("\t", $line);
$array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}
Could anyone see what I am doing wrong here? Thank you.
Upvotes: 0
Views: 1273
Reputation: 496
Your code looks good. I did add one if statement to make sure splode was 5 long before assigning it. This is protection against a possible blank line at the end of a file.
I ran it on a test file here with a few lines and it processed correctly and outputted as expected.
Depending on how you're creating this file - could you have a '\r' or a '\r\n' on the end of each line instead of just a \n?? This is something you'd need to check - maybe a hex editor, but I still think your code should run ok (unless it's just a \r) as long as there's enough tabs to satisfy the 5 on each line (which I conditionaled for in my suggestion).
function read_file()
{
$file = "orders.txt";
$array = array();
if (file_exists($file)) {
echo "Get";
$myfile = fopen($file, "r");
$data = file_get_contents($file);
$lines = explode("\n", $data);
var_dump($lines);
foreach ($lines as $line) {
$splode = explode("\t", $line);
if (sizeof($splode) >= 5) $array[] = array(
"Name" => $splode[0],
"Time" => $splode[1],
"Quant" => $splode[2],
"Type" => $splode[3],
"Price" => $splode[4],
);
}
fclose($myfile);
}
return $array;
}
Upvotes: 1