user1449369
user1449369

Reputation: 67

Function explode simple text file

I have a simple text file (see below).

abc|1356243309
zzz|1356239986
yyy|1356242423

I want to simply extract all names before |. So the output should look like:

abc
zzz
yyy

Below is the string I've attempted to use. I've also tried file('visitornames.txt') etc. I'm not sure what im doing wrong :(. Tried a lot of things.

$string = file_get_contents('visitornames.txt');
$names = explode('|', $string);
foreach($names as $key) {

echo $key . '"<br/>';

}

No errors, but its simply not doing it correctly.

Upvotes: 0

Views: 232

Answers (2)

hakre
hakre

Reputation: 198116

You can extract all lines of a file with the file function, then take each first part of the explode and assign it to the result:

$names = array();
foreach (file('visitornames.txt') as $line)
{
    list($names[]) = explode('|', $line, 2);
}

Alternatively there is SplFileObject that is similar but you can more easily extend from it:

class Names extends SplFileObject
{
    public function current() {
        list($name) = explode('|', parent::current(), 2);
        return $name;
    }
}

$names = new Names('visitornames.txt');

foreach ($names as $name)
{
    echo $name, "<br />\n";
}

Upvotes: 0

TCFDS
TCFDS

Reputation: 622

I would use file-function instead of file_get_contents. It returns file as array where every line is own item. Then you can foreach file content array. Variable you are looking for is first part of the line and that's why you can just echo $names[0].

$file = file('visitornames.txt');
foreach ($file AS $line) {
    $names = explode('|', $line);
    echo $names[0] . '<br/>';
}

Upvotes: 5

Related Questions