简体   繁体   English

遍历CSV并使用每个结果解析JSON查询

[英]Looping through CSV and parsing a JSON query using each result

So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse. 因此,尽管经过了数小时的摆弄,但我仍无法理解为什么我的JSON查询仅返回我要解析的CSV / TXT文件中最后一行的结果。

Here is the code: 这是代码:

//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';

//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';

$page = join("",file("$csv_location"));
$kw = explode("\n", $page);

for($i=0;$i<count($kw);$i++){
    $destination = $kw[$i];
    echo $destination;
    $raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
    $request_url = str_replace(' ', '', $raw_url);

    $getJson = file_get_contents($request_url);
    $routes = json_decode($getJson);

    $result = $routes->routes[0]->legs[0]->distance->value;
    echo $result . '<br>';
}

The result I get looks like this: 我得到的结果看起来像这样:

Distance by Post Code Generator v0.1 by Phil Hughes 

RG12 0GA 
RG12 0GB 
RG12 0GC 
RG12 0GD4066

Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see. 如您所见,“ 4066”是RG12 0GD邮政编码的正确变量,但其他变量均未返回结果。

Please help. 请帮忙。

Your 你的

join("",file("$csv_location"));

concatenated all lines feom the file to a single line without separator. 将文件中的所有行串联到没有分隔符的一行中。 The following explode() sees no newlines any more. 以下explode()不再看到换行符。 So you are working on one line only. 因此,您只在一行上工作。 count($kw) always evaluates to 1 and your loop runs only one time. count($ kw)始终求值为1,并且循环仅运行一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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