parsing a text file in php and retrieving information
I'm trying to parse a basic text file in PHP, but not sure where to begin.
The file contains info such as:
http://pastebin.com/ahqtJzH6
You'll notice that the information I need to capture is split开发者_运维问答 up by new lines. Right now I'm just throwing every new line into a $applicant[] array, but I need to get rid of the preceding text in each line.
I was thinking I probably need to use regex or something to single out just the data I need. Ideas?
Thank you!
Without using regex, you can do this:
$fp = fopen('textfile.txt', 'r');
$return = array();
while ($line = fgets($fp)) {
$parts = explode(':', $line);
$key = trim($parts[0]);
unset($parts[0]);
$value = str_replace("\n", '', implode(':', $parts));
$return[$key] = trim($value);
}
print_r($return);
Would output something like:
Array (
[Applicant SSN] => 123456789
[Applicant Name] => BOB, BOB
...
)
You could use strpos
to find the : character and then grab everything after that. You can use trim
to get rid of extra whitespace.
$lines = file('textfile.txt');
foreach ($lines as $line) {
$p = strpos($line, ':');
if ($p!==false) {
$key = trim(substr($line, 0, $p));
$value = trim(substr($line, $p+1));
// do whatever with your key & value
}
}
精彩评论