• 13

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

PHP - parsing a txt file

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

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.


You can do that easily this way

$txt_file    = file_get_contents('path/to/file.txt');
$rows        = explode("\n", $txt_file);

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

  • 62
Reply Report
    • @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?
      • 2
    • @terrid25: Did you try my new (updated) code? If yes, please post the code you are using for var_dump().
    • @terrid25: I am using the following code: var_export(explode(',', $info[1]['images']));. It outputs: array ( 0 => 'image_1.jpg', 1 => 'image_2.jpg', ).
    • 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(" ", $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']); }
      • 2
    • @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?

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])
  • 8
Reply Report

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.


  • 6
Reply Report

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)));
  • 4
Reply Report

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;
  • 0
Reply Report

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);
  • 0
Reply Report

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; 
        } // skip first line
        $texts = explode('^', $line);
        $data[] = array_combine($keys,$texts);
    return $data;
  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions