我正在使用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)';
}
?>
基本上,只要提供的源/目的地不包含需要编码的字符,您的代码就可以工作。
当它包含这样的字符时(例如英国邮政编码通常包含空格),您必须对这些参数进行编码:
$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
之前删除@
以获取错误消息(如果有)。