Question

I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!

Was it helpful?

Solution

You can read a file into an array of lines and do all the splitting with:

$lines = file("filename");
foreach($lines as $line) {
    $parts = explode("|", $line);
    // do the database inserts here
}

If you already have all the text in a variable as you said (e.g., with something like file_get_contents() ), you can explode on \n first and then do the same foreach statement as above.

OTHER TIPS

If you are reading out of your textarea post, you can use the explode function using the newline character as your separator to get each "line" in the variable as a new element of an array, then you can do explode on your array elements.

i.e.

$sometext = "balh | balh blah| more blah \n extra balh |some blah |this blah";

$lines = explode("\n", $sometext);
foreach($lines as $oneLine)
{
    $lineElements[] = explode("|", $oneLine);
}

then you have a 2d array of your elems.

If you are reading out of a file, you can simply use the file function documented here:

http://us2.php.net/manual/en/function.file.php

to get each line of the file as an element of an array.

There is a ready-built PHP parsing library that can auto-detect the CSV format.

Example:

$reader = new Dfp_Datafeed_File_Reader();
$reader->setLocation('test.csv');

foreach ($reader AS $record) {
    print_r($record);
}

It's available to download here, and there's some documentation here.

If the file is small, you can use file() to read it into an array, one line per element.

Failing that, read the file in loop using fgets()

$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
   $buffer = fgets($handle, 4096);
   echo $buffer;
}
fclose($handle);

You can use explode to get both:

$myFile = "File.txt";
$fh = fopen($myFile, 'r');
$data = fread($fh);
fclose($fh);
$newLines = explode("\n",$data);

foreach($newLines as $s)
{
  $parsed = explode("|",$s);
  foreach($parsed as $item)
  {
    // do your db load here
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top