36

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

adarshr
  • 61,315
  • 23
  • 138
  • 167
terrid25
  • 1,926
  • 8
  • 46
  • 87

9 Answers9

69

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']);

Michiel Pater
  • 22,377
  • 5
  • 43
  • 57
  • @Michiel Pater thanks for the headsup, the problem is, when I get the images, var_dump() just outputs: IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123 any ideas? – terrid25 Mar 14 '11 at 14:27
  • @terrid25: Did you try my new (updated) code? If yes, please post the code you are using for `var_dump()`. – Michiel Pater Mar 14 '11 at 14:29
  • @terrid25: I am using the following code: `var_export(explode(',', $info[1]['images']));`. It outputs: `array ( 0 => 'image_1.jpg', 1 => 'image_2.jpg', )`. – Michiel Pater Mar 14 '11 at 14:32
  • Yes I tried the updated code. `var_dump($info[1]['images']);` gives me NULL. My full code is `$txt_file = file_get_contents('test.txt'); $rows = explode("\r\n", $txt_file); foreach($rows as $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]; var_dump($info[1]['images']); }` – terrid25 Mar 14 '11 at 14:36
  • @terrid25: You must be doing something different then. When I try using the same code it outputs `string(23) "image_1.jpg,image_2.jpg"`. Are you having the same content in your text file as you posted in your question? – Michiel Pater Mar 14 '11 at 14:41
  • @terrid25: You should put the `var_dump()` after the `}`. Also, try using `$first_row_images = explode(',', $info[0]['images']);` and then use `var_export($first_row_images)` to see the images seperated. – Michiel Pater Mar 14 '11 at 14:43
  • Yeah I copied and pasted. My out put now is `array ( 0 => 'IMAGES 123', )` – terrid25 Mar 14 '11 at 14:51
  • @terrid25: Allright, I have updated my question. I have changed `"\r\n"` to `"\n"`. Maybe this will solve your problem. Also, I have changed `$first_row_images = explode(',', $info[0]['images']);` to `$first_row_images = explode(',', $info[1]['images']);`, so you will get the data instead of the headers. – Michiel Pater Mar 14 '11 at 14:59
  • @Michiel Pater ok some improvement. The problem is though, I need all the info for each of the rows, apart from the header values. The code you have done for me, only returns the first rows values. Thanks – terrid25 Mar 14 '11 at 15:20
  • @terrid25: I have updated my answer again. Now it will directly output all information of each row. The header is removed using the function `array_shift()`. Please let me know when you have made some progress. – Michiel Pater Mar 14 '11 at 15:33
  • @terrid25: I have made a little change to the `array_shift()` part. It is working for me. – Michiel Pater Mar 14 '11 at 15:38
  • @Michiel Pater can I ask where $info is set? Thanks – terrid25 Mar 17 '11 at 13:39
  • This doesn't infer the headings from the header row. – Lloyd Moore Jan 28 '16 at 10:29
  • file_get_contents() and explode can be done in one go with file function : file('path/to/file.txt', FILE_IGNORE_NEW_LINES) The flag can be removed if $data is trimmed before use (flag removes newline character) – Bevelopper Mar 24 '21 at 09:23
8

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])
    );
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
7

By far the best and simplest example of this I have come accross is quite simply the file() method.

$array = file("myfile");
foreach($array as $line)
       {
           echo $line;
       }

This will display all the lines in the file, this is also applicable for a remote URL.

Simple and clear.

REF : IBM PHP Parse

Pogrindis
  • 7,755
  • 5
  • 31
  • 44
5

I would like to contribute a file that provides atomic data structures.

$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
    function($x) use ($keys){
        return array_combine($keys, explode('^', trim($x)));
    }, 
    $lines
);
Lloyd Moore
  • 3,117
  • 1
  • 32
  • 32
3

Try fgetcsv() with ^ as the separator character:

$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);

http://www.w3schools.com/php/func_filesystem_fgetcsv.asp

adarshr
  • 61,315
  • 23
  • 138
  • 167
0

My solution

function parseTextFile($file){
    if( !$file = file_get_contents($file))
        throw new Exception('No file was found!!');
    $data = [];
    $firstLine = true;
    foreach(explode("\n", $file) as $line) {
        if($firstLine) { 
            $keys=explode('^', $line);
            $firstLine = false; 
            continue; 
        } // skip first line
        $texts = explode('^', $line);
        $data[] = array_combine($keys,$texts);
    }
    return $data;
}
Marcos
  • 1
0
<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
tawfekov
  • 5,084
  • 3
  • 28
  • 51
0

Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...

$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
   $details[] = $line;
}
fclose($fh);
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:

list($number, $status, $text, $images) = explode("^", $data);

$splited_images= preg_split(',', $images);
jwillmer
  • 3,570
  • 5
  • 37
  • 73