Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing A Data Feed

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!

like image 595
zuk1 Avatar asked May 09 '26 17:05

zuk1


2 Answers

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.

like image 67
Randy Avatar answered May 11 '26 06:05

Randy


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:

https://www.php.net/manual/en/function.file.php

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

like image 37
Zak Avatar answered May 11 '26 05:05

Zak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!