I have the following notepad file;
dbName:
tableName:
numberOfFields:
I am trying to write a php app which assigns the value of dbName to $dbName, tableName to $tableName and numberOfFields to $numFields.
My code is:
$handle = @fopen("config.txt", "r"开发者_运维知识库);
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
list($dbName, $tableName, $numFields) = explode(":", "$buffer");
}
fclose($handle);
}
however, ":" doesn't work as there are line breaks in between dbName and table Name. How do I explode $buffer, keeping the line breaks in the notepad file?
Thank you.
Have a look at the file
function. It takes care of opening and reading the file, and returns an array of lines from the file. You could then iterate through the array and operate on each line individually.
http://us.php.net/manual/en/function.file.php
you can do this:
$data=file_get_contents("file");
$s = preg_split("/\n\n+/m", $data);
print_r($s);
You can use the chr($INT); function to look for the line break in your explode call.
Your can find more on the chr function here:
http://php.net/manual/en/function.chr.php
Add you can find the ascii chars for line break at:
http://www.asciitable.com/
fgets
returns only one line. There is no way $buffer
would ever have all three items at once, so that assignment to list()
is wrong. For the first line, explode()
will return an array with two items: "dbName"
(text before the colon) and ""
(text after the colon).
Does this work:
list ($dbName, $tableName, $numFields) = explode (':', implode ('', file ('config.txt')));
If you're sure of the line contents, and the file will not grow arbitrarily large:
1 <?php
2
3 $handle = @fopen("config.txt", "r");
4 if ($handle) {
5 $buffer = "";
6 while (!feof($handle)) {
7 $buffer = $buffer . trim(fgets($handle, 4096));
8 }
9 fclose($handle);
10
11 list($dbName, $tableName, $numFields) = explode(":", $buffer);
12 }
13
14 ?>
The while loop will go through all the lines and concatenate onto the same buffer after removing whitespace. This leaves just the content separated by ":". This is now amenable to explode.
As Nicolas wrote, feof gets one line at a time, so the list assignment needs to happen outside the loop.
精彩评论