Retrieving info from a file

为君一笑 提交于 2019-12-24 11:36:14

问题


This code retrieves information from another site:

<?php


    $location = $ident;

get_taf($location);

function get_taf($location) {
$fileName = "ftp://tgftp.nws.noaa.gov/data/forecasts/taf/stations/$location.TXT";
    $taf = '';
    $fileData = @file($fileName);

    if ($fileData != false) {
        list($i, $date) = each($fileData);

        $utc = strtotime(trim($date));
        $time = date("D, jS M Y Hi",$utc);

        while (list($i, $line) = each($fileData)) {
            $taf .= ' ' . trim($line);
            }
        $taf = trim(str_replace('  ', ' ', $taf));
        }


if(!empty($taf)){
    echo "Issued: $time Z
    <br><br>
    $taf";
    } else {
    echo 'TAF not available';
    }
}

?>

What its suppose to look like:

 TAF KLBX 160541Z 1606/1706 15009KT P6SM FEW009 BKN013 OVC030 
 FM160900 15005KT P6SM SCT010 BKN035 
 FM161600 16010KT P6SM VCSH SCT012 BKN030 
 FM161900 18012KT P6SM SCT025 BKN040 
 FM170000 16005KT P6SM SCT012 BKN022

What it ends up looking like:

TAF KLBX 160541Z 1606/1706 15009KT P6SM FEW009 BKN013 OVC030 FM160900 15005KT P6SM SCT010 BKN035 FM161600 16010KT P6SM VCSH SCT012 BKN030 FM161900 18012KT P6SM SCT025 BKN040 FM170000 16005KT P6SM SCT012 BKN022

How do I maintain the spacing with the rows???

It is putting all the info on 1 line and it looks like a paragraoh instead a list.

Thanks


回答1:


Your output contains newline bytes, but in webpages those line breaks are usually treated as regular spacing characters and not as an actual line break (the br tag is used for hard breaks instead). PHP has a function to convert line breaks to br tags called nl2br, so you could do this:

$taf = nl2br(trim(str_replace('  ', ' ', $taf)), false);

Since you're trimming the line endings of every line you'll also have to modify something to either preserve them (by using trim with two parameters or by using just ltrim) or re-add them manually like this:

$taf .= ' ' . trim($line) . "\n";

You could also append the <br> tags directly, that would save you the conversion. Another possibility would be to just preserve/add the line endings and wrap the output in a <pre> section, this will eliminate the need of break-tags.




回答2:


Modify the following line

 $taf .= ' ' . trim($line);

Using the PHP End of Line constant, like so:

 $taf .= ' ' . trim($line).PHP_EOL;


来源:https://stackoverflow.com/questions/9733122/retrieving-info-from-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!