user235621
user235621

Reputation:

Parsing Text File into Variables with PHP

Need some help with parsing a text file into PHP. The file is generated by a PHP script, so I don't have control over the content formatting. The text file looks like this:

7/4/2013-7/4/2013
Best Legs in a Kilt
To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.
kilt.jpg
1,1,0,
-

7/8/2013-7/23/2013
Hot Legs
Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.
hotstuff.jpg
1,1,0,
-

The code that I have thus far is:

$content = file_get_contents('DC_PictureCalendar/admin/database/cal2data.txt');

list($date, $showname, $summary, $image, $notneeded, $notneeded2) = explode("\n", $content);

echo 'Show Name' . $showname . '<br/>';

This only gets me the first show title, I need to grab all of them. I'm sure a For loop would do it, but not sure how to do it based on the contents of the file. All I need is the 2nd line (show title) and the 4th line (image). Any help? Thanks in advance.

Upvotes: 1

Views: 2926

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

If you are reading the entire file into an array anyway, then just use file() which will read each line into an array.

$content = file('DC_PictureCalendar/admin/database/cal2data.txt', FILE_IGNORE_NEW_LINES);

You can then filter all the lines you don't want like this

$content = array_diff($content, array('1,1,0', '-'));

You can then break into chunks of 4 lines each (i.e. one item per entry)

$content_chunked = array_chunk($content, 4);

This would give you an array like

Array(
    0 => Array(
        0 => '7/4/2013-7/4/2013',
        1 => 'Best Legs in a Kilt',
        2 => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
        3 => 'kilt.jpg'
    ),
    1 => Array(
        0 => '7/8/2013-7/23/2013',
        1 => 'Hot Legs',
        2 => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
        3 => 'hotstuff.jpg'
    ) ... etc.
)

I would then map this array into a useful array of objects with property names that are meaningful to you:

$items = array_map(function($array)) {
    $item = new StdClass;
    $item->date = $array[0];
    $item->showname = $array[1];
    $item->summary = $array[2];
    $item->image = $array[3];
    return $item;
}, $content_chunked);

That would leave you with an array of objects like:

Array(
    0 => stdClass(
        'date' => '7/4/2013-7/4/2013',
        'showname' => 'Best Legs in a Kilt',
        'summary'  => 'To start the summer off with a bang, the Playhouse has teamed up with the folks at The Festival.',
        'image' => 'kilt.jpg'
    ),
    1 => stdClass(
        'date' => '7/8/2013-7/23/2013',
        'showname' => 'Hot Legs',
        'summary' => 'Yes, folks, it's all platform shoes, leisure suits, and crazy hair-do's.',
        'image' => 'hotstuff.jpg'
    ) ... etc.
)

Upvotes: 2

Related Questions