Data Feed Analysis

I am not the best in PHP and will be very grateful if anyone can help. Basically I need to parse every row of data and just get every bit of information between each "|" - then I can add it to the database. I think I can process information between the "|" using explode, but I need a little help in parsing each line from a text file as a singular. Infact, to make it even simpler, I just need to use each line of the variable, I will send the contents of the variable using a text field and form. Any help would be greatly appreciated!

+3
source share
5 answers

You can read the file in an array of strings 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 (for example, with something like file_get_contents ()), you can first explode in \ n and then make the same foreach statement as above.

+4
source

If you are reading your post in textarea, you can use the break function using the newline character as a separator to get each "line" in the variable as a new array element, then you can 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 ale.

If you are reading a file, you can simply use the file function registered here:

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

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

+2

PHP, CSV.

:

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

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

, .

+1

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

Otherwise, read the file in a loop using fgets ()

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

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
  }
}
0
source

Source: https://habr.com/ru/post/1698501/


All Articles