5

I´m having trouble exploding contents of a .txt file (structure below):

    01Name 1 
    02whatever contents
    03whatever contents
    -------------------
    01Name 2
    02whatever contents
    03whatever contents

As you can see, the "delimiter" is "-------------------". Now, the question is: how to explode this file into an array, so I can search for a specific name and display that block´s contents? I´ve tried to explode like this:

  header("Content-type:text/plain");
  $file = fopen("cc/cc.txt", "r");


  while (!feof($file)) {
    $lot = fgets($file);
    $chunk = explode("-------------------",$lot);

    print_r($chunk);

  }

  fclose($file);             

And got this as a result:

    Array
    (
        [0] => 01Name 1 

    )
    Array
    (
        [0] => 02whatever contents

    )
    Array
    (
        [0] => 03whatever contents

    )
    Array
    (
        [0] => -------------------

    )
    Array
    (
        [0] => 01Name 2

    )
    Array
    (
        [0] => 02whatever contents

    )
    Array
    (
        [0] => 03whatever contents
    )        

when i wanted to get this as a result:

    Array
    (
        [0] => 01Name 1
        [1] => 02whatever contents
        [2] => 03whatever contents

    )
    Array
    (
        [0] => 01Name 2
        [1] => 02whatever contents
        [2] => 03whatever contents
    )

I´ve searched PHP; assigning fgets() output to an array and Read each line of txt file to new array element , with no luck.

Any thoughts?

2
  • 1
    you can't explode a txt file, you can explode contents of txt file ...
    – Mr. Alien
    Oct 3, 2012 at 16:19
  • ok.. edited my question! Oct 3, 2012 at 16:23

4 Answers 4

5

You can use the following

$result = array();
$file = explode("-------------------", file_get_contents("cc/cc.txt"));
foreach ( $file as $content ) {
    $result[] = array_filter(array_map("trim", explode("\n", $content)));
}
var_dump($result);

Output

array
  0 => 
    array
      0 => string '01Name 1' (length=8)
      1 => string '02whatever contents' (length=19)
      2 => string '03whatever contents' (length=19)
  1 => 
    array
      1 => string '01Name 2' (length=8)
      2 => string '02whatever contents' (length=19)
      3 => string '03whatever contents' (length=19)

You can take it further

$result = array();
$file = explode("-------------------", file_get_contents("cc/cc.txt"));
foreach ( $file as $content ) 
{
    foreach(array_filter(array_map("trim",explode("\n", $content))) as $line)
    {
        list($key,$value) = explode(" ", $line);
        $result[$key] = $value ;
    }
}
var_dump($result);

Output

array
  '01Name' => string '2' (length=1)
  '02whatever' => string 'contents' (length=8)
  '03whatever' => string 'contents' (length=8)
4
  • Your first option did it! Now it's just a matter of looping through arrays...Thanks!!! Oct 3, 2012 at 16:52
  • You are welcome i can see you are new. You should also accept see : meta.stackexchange.com/questions/16721/…
    – Baba
    Oct 3, 2012 at 16:53
  • You accepted another answer not mine ... you can only accept one answer at a time
    – Baba
    Oct 3, 2012 at 17:00
  • Thanks I really appreciate @MrsSammartino
    – Baba
    Oct 3, 2012 at 18:08
0

Firstly you should use file() to read and split up a file line-wise. That's a built-in specifically for that purpose.

Your check for "-------------------" fails because you didn't take the trailing linebreaks (\r\n etc.) into account. (Use FILE_IGNORE_NEW_LINES for the file() function as one solution). Though it might be better to use a regex here:

$lines = file($filename);
foreach ($lines as $line) {
    if (preg_match('/^\s*---------+\R*$/', $line)) { ... }
}

A bit redundant this way, but more resilient.

You might as well read the whole file with file_get_contents and split out text blocks with preg_split instead.

1
  • Preg_split does not apply in this case..other than that, it works fine! Thanks! Oct 3, 2012 at 17:04
0

If your file is consistently formatted, having three lines per block of data, you could simply parse it that way. Here I am creating a 2-dimensional array of the whole file:

<?php

header("Content-type:text/plain");
$file = fopen("cc.txt", "r");

$alldata = array();
$index = 0;
while (!feof($file))
{
    $alldata[$index]['name'] = fgets($file);
    $alldata[$index]['c1'] = fgets($file);
    $alldata[$index]['c2'] = fgets($file);
    fgets($file); // throw away delimiter line
    $index++;
}
fclose($file);  

print_r($alldata);
?>

This outputs:

Array
(
    [0] => Array
        (
            [name] => 01Name 1 
            [c1] => 02whatever contents
            [c2] => 03whatever contents
        )
    [1] => Array
        (
            [name] => 01Name 2
            [c1] => 02whatever contents
            [c2] => 03whatever contents
        )
)
1
  • Unfortunately, I just edited my txt file for readability... the actual text file have approx. 2800 lines... and the number of lines are inconsistent on each block.. Oct 3, 2012 at 16:43
0
$c      = file_get_contents($file);
$lines  = explode("-------------------", $c);
foreach ($lines as $l) {
    if (strpos($l, 'keyword') !== false) {
        echo $l;
        die();
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.