显示文本文件中的数据

时间:2017-02-08 11:10:24

标签: php

我是php的新手。问题是我有一个包含这些数据的文本文件。数据以这种方式在文本文件中进行排序。

1

总理医院 PTB 1600,Road 13
索尔福德市
5000英格兰曼彻斯特

2

TSH医院 伯明翰路760号 82000英国伯明翰,

3

圣安德鲁医院
58,城市道路 700悉尼,澳大利亚

4

Andrew Clinic
樱花路11号 90000,珀斯
澳大利亚

我设法使用以下代码阅读文本文件:

$file = fopen("newFile.txt", "r") or die("Unable to open file!");
while (!feof($file)){   
    $data = fgets($file); 
    echo str_replace('\r\n','',$data);
}

fclose($file);

但输出是diplay,如下所示:

1 Premier Hospital PTB 1600,Road 13 Salford City 5000 Manchester,England 2 TSH Hospital 760,Birmingham Road 82000 Birmingham,England 3 St Andrew Hospital 58,City Road 700 Sydney,Australia 4 Andrew Clinic No. 11,Cherry Road 90000 ,珀斯澳大利亚

我的问题是如何在不更改文本文件的情况下使用php将输出更改为:

1 Premier Hospital PTB 1600,Road 13 Salford City 5000 Manchester,England
2 TSH医院760,伯明翰路82000伯明翰,英格兰 3 St Andrew Hospital 58,City Road 700 Sydney,Australia
4 Andrew Clinic No. 11,Cherry Road 90000,Perth Australia

2 个答案:

答案 0 :(得分:0)

在这种情况下,您需要逐行阅读内容:

<?php

$fp = fopen('sample.txt','r');
while ($text = fgets($fp)) {
  echo $text;
}
fclose($fp);
?>

答案 1 :(得分:0)

使用fgets逐行获取文本:

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
    }

    fclose($handle);
} else {
    // error opening the file.
} 
相关问题