Monday 15 February 2010

php - Splitting txt file delimited by tabs into multidimensional associative array -



php - Splitting txt file delimited by tabs into multidimensional associative array -

i trying read input file looks this:

annie tuesday oct 7 @ 08:32 pm 1 cappuccino 2.5

it delimited tabs. trying read file, called orders.txt, , place associative array $array. code have far. have tried several different versions, 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 $line) { $splode = explode("\t", $line); $array[] = array( "name" => $splode[0], "time" => $splode[1], "quant" => $splode[2], "type" => $splode[3], "price" => $splode[4], ); } fclose($myfile); } homecoming $array; }

could see doing wrong here? give thanks you.

your code looks good. did add together 1 if statement create sure splode 5 long before assigning it. protection against possible blank line @ end of file.

i ran on test file here few lines , processed correctly , outputted expected.

depending on how you're creating file - have '\r' or '\r\n' on end of each line instead of \n?? you'd need check - maybe hex editor, still think code should run ok (unless it's \r) long there's plenty tabs satisfy 5 on each line (which conditionaled in 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 $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); } homecoming $array; }

php arrays multidimensional-array

No comments:

Post a Comment