GuzzleHttp请求文本文件而不会丢失换行符

时间:2018-01-26 08:26:21

标签: php guzzle guzzlehttp

我从国家数据浮标中心(NDBC)提取数据,我正在抓取latest observations的文本文件,如果我使用AJAX在JavaScript中执行此操作,我会获取新行并可以解析数据很容易,但是使用PHP(特别是GuzzleHttp)时,新行就会丢失,因为它们不存在,所以我无法在新行上进行解析。

请求

$url = "http://www.ndbc.noaa.gov/data/latest_obs/41004.txt";
$res = $this->httpClient->request('GET', $url);

响应

Station 41004 32° 30.0' N 79° 6.0' W 2:50 am EST 0750 GMT 01/26/18 Wind: ENE (60°), 15.5 kt Gust: 19.4 kt Seas: 3.6 ft Peak Period: 5 sec Pres: 30.54 Air Temp: 55.6 °F Water Temp: 70.2 °F Dew Point: 40.5 °F Wave Summary 2:40 am EST 0700 GMT 01/26/18 Swell: 1.3 ft Period: 10.0 sec Direction: SE Wind Wave: 3.3 ft Period: 5.0 sec Direction: ENE

而不是像:

Station 41004
32° 30.0' N  79° 6.0' W

2:20 am EST
0720 GMT 01/26/18
Wind: ENE (60°), 13.6 kt
Gust: 19.4 kt
Pres: 30.54
Air Temp: 55.0 °F
Water Temp: 70.3 °F
Dew Point: 40.1 °F

Wave Summary
1:40 am EST
0600 GMT 01/26/18
Swell: 1.3 ft
Period: 8.3 sec
Direction: ENE
Wind Wave: 3.3 ft
Period: 4.3 sec
Direction: NE

有没有办法维护换行符?

1 个答案:

答案 0 :(得分:1)

我认为使用此代码的新行字符至少对我而言:

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://www.ndbc.noaa.gov/data/latest_obs/41004.txt');
$result = utf8_encode($res->getBody()->getContents());

使用以下任一方法打印结果:

echo '<pre>' . $result . '</pre>';
echo str_replace("\n", '<br>', $result);

给我这个:

Station 41004
32° 30.0' N  79° 6.0' W

3:30 am EST
0830 GMT 01/26/18
Wind: ENE (60°), 15.5 kt
Gust: 19.4 kt
Pres: 30.54
Air Temp: 55.8 °F
Water Temp: 70.0 °F
Dew Point: 40.1 °F

Wave Summary
2:40 am EST
0700 GMT 01/26/18
Swell: 1.3 ft
Period: 10.0 sec
Direction: SE
Wind Wave: 3.3 ft
Period: 5.0 sec
Direction: ENE
Station 41004
32° 30.0' N 79° 6.0' W

3:30 am EST
0830 GMT 01/26/18
Wind: ENE (60°), 15.5 kt
Gust: 19.4 kt
Pres: 30.54
Air Temp: 55.8 °F
Water Temp: 70.0 °F
Dew Point: 40.1 °F

Wave Summary
2:40 am EST
0700 GMT 01/26/18
Swell: 1.3 ft
Period: 10.0 sec
Direction: SE
Wind Wave: 3.3 ft
Period: 5.0 sec
Direction: ENE