简体   繁体   中英

Line breaks in HTML source when reading in text file with PHP

When reading in a text file via PHP as followed:

$file_handle = fopen("L:\\file.txt", "rb"); 
while (!feof($file_handle) ) 
{
    $line_of_text = fgets($file_handle); 
    $parts = explode('=', $line_of_text); 
    echo "<option value=\"$parts[0]\">$parts[0]</option>"; 
}
fclose($file_handle);   

... the HTML source code ends up looking like:

<option value="AACM
">AACM
</option><option value="Academic Registry
">Academic Registry
</option><option value="Admin
">Admin

.. and so on. Very messy! Is there a way to prevent it? Ideally I'd like it formatted properly as:

<option value="AACM">AACM</option>
<option value="Academic Registry">Academic Registry</option>

... etc.

Is this possible?

Thanks :)

echo "<option value=\"".trim($parts[0])."\">".trim($parts[0])."</option>"; 

您正在寻找trim()函数来删除前导和尾随空格。

Remove this:

$parts = explode('=', $line_of_text); 

Acctuly an easier and faster way to read a file without doing something line by line is file_get_contents() Example: echo file_get_contents("L:\\\\file.txt");

But if you want to read the file line by line heres an

<?php
$filename = "L:\\file.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp)) {
   $line = fgets($fp, 1024);
   echo "$line\n";
}
?>

Sources: http://php.net/manual/en/function.file-get-contents.php http://www.codemiles.com/php-tutorials/reading-a-file-line-by-line-in-php-t1484.html

I didn't try out, but i think this should work:

$file_handle = fopen("L:\\file.txt", "rb"); 
while (!feof($file_handle) ) 
{
    $line_of_text = fgets($file_handle); 
    $parts = explode('=', $line_of_text); 
    $option = "<option value=\"$parts[0]\">$parts[0]</option>";
    $new_option = preg_replace("/[\n\r]/","",$option) . "\n";
    echo $new_option;
}
fclose($file_handle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM