无效参数foreach()google api

时间:2015-04-27 07:14:29

标签: php wordpress google-maps-api-3

我正在使用wordpress,我正在尝试显示两个邮政编码之间的距离。我有这个工作,但它突然停止了,我不知道为什么因为我没有改变代码。

我认为我没有错过以下代码中的任何内容?

错误是:

  

警告:在第135行的/single-project.php中为foreach()提供的参数无效

代码是:

<?php
$my_custom_field = get_post_meta(get_the_ID(), 'app_collection-postcode', true);
$my_custom_field2 = get_post_meta(get_the_ID(), 'app_delivery-postcode', true);
//**Get rid of any spaces either side**
            $my_custom_field_trim = trim($my_custom_field);
            $my_custom_field_trim2 = trim($my_custom_field2);
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$my_custom_field_trim&destinations=$my_custom_field_trim2&units=imperial&mode=driving&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
foreach($result['rows'] as $distance) { 
    echo '' . $distance['elements'][0]['distance']['text'] . ' (' . $distance['elements'][0]['duration']['text'] . ' in current traffic)';
}
 ?>

1 个答案:

答案 0 :(得分:0)

基本上您的代码应该可以工作,只要提供的来源/目的地不包含需要进行urlencoded的字符。

当它包含这些字符时(例如UK-postcodes通常包含空格),您必须对这些参数进行编码:

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?"
        .http_build_query(array('origins'      => $my_custom_field_trim,
                                'destinations' => $my_custom_field_trim2,
                                'units'        => 'imperial',
                                'mode'         => 'driving',
                                'language'     => 'en-EN'));

但是,对于开发,您应该在@之前删除file_get_contents以获取错误消息(如果有)。