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


Looping through CSV and parsing a JSON query using each result

所以尽管摆弄了几个小时,我还是无法理解为什么我的JSON查询只返回我试图解析的CSV/TXT文件的最后一行的结果。

代码如下:

//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>';
}

我得到的结果是这样的:

Distance by Post Code Generator v0.1 by Phil Hughes 
RG12 0GA 
RG12 0GB 
RG12 0GC 
RG12 0GD4066

其中'4066'是RG12 0GD邮编的正确变量,但其他变量都没有返回结果,如您所见。

请帮。

您的

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

将文件中的所有行连接为一行,不带分隔符。下面的explosion()不再看到换行符。所以你只在一行上工作。Count ($kw)总是求值为1,循环只运行一次。