Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - parsing a txt file

I have a .txt file that has the following details:

ID^NAME^DESCRIPTION^IMAGES 123^test^Some text goes here^image_1.jpg,image_2.jpg 133^hello^some other test^image_3456.jpg,image_89.jpg 

What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.

Thanks

like image 423
terrid25 Avatar asked Mar 14 '11 13:03

terrid25


2 Answers

You can do that easily this way

$txt_file    = file_get_contents('path/to/file.txt'); $rows        = explode("\n", $txt_file); array_shift($rows);  foreach($rows as $row => $data) {     //get row data     $row_data = explode('^', $data);      $info[$row]['id']           = $row_data[0];     $info[$row]['name']         = $row_data[1];     $info[$row]['description']  = $row_data[2];     $info[$row]['images']       = $row_data[3];      //display data     echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';     echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';     echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';     echo 'Row ' . $row . ' IMAGES:<br />';      //display images     $row_images = explode(',', $info[$row]['images']);      foreach($row_images as $row_image)     {         echo ' - ' . $row_image . '<br />';     }      echo '<br />'; }

First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.

After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.

If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);

like image 54
Michiel Pater Avatar answered Oct 16 '22 12:10

Michiel Pater


Use explode() or fgetcsv():

$values = explode('^', $string); 

Or, if you want something nicer:

$data = array(); $firstLine = true; foreach(explode("\n", $string) as $line) {     if($firstLine) { $firstLine = false; continue; } // skip first line     $row = explode('^', $line);     $data[] = array(         'id' => (int)$row[0],         'name' => $row[1],         'description' => $row[2],         'images' => explode(',', $row[3])     ); } 
like image 34
ThiefMaster Avatar answered Oct 16 '22 11:10

ThiefMaster