php 中未定义的偏移错误?

Undefined offset error in php?

大家好!

我正在尝试将 OSM(Overpass Turbo)中的 JSON/XML 解析为 php 并尝试获取限速值。我能够得到值,但在此之前有一些错误

"Undefined offset: 1 in C:\xampp\htdocs\android_connect\test-osm.php on line 44",也就是这段代码if ($temp[1]=="maxspeed")

我想做的是:

首先:从 OSM 获得结果后,我将带有“<”标签的响应分解为一个名为 'resultArr'

的数组

第二:然后,我将带有“ 标签的 'resultArr' 分解为一个名为 "temp".

的数组

下面是 php 文件:

<?php
//$lat  = isset($_GET['lat']) ? floatval($_GET['lat']) :  "";
//$lng = isset($_GET['lng']) ? floatval($_GET['lng']) :  "";

$lat  = 24.883968;
$lng = 55.544899;

//$latm = -0.00015 + $lat;
$latm = 54.580460;
//echo $latm. "\n";
//$latp = 0.00015 + $lat;
$latp = 54.580860;
//echo $latp. "\n";
//$lngm = -0.00015 + $lng;
$lngm = 24.326180;
//echo $lngm. "\n";
//$lngp = 0.00015 + $lng;
$lngp = 24.336580;
//echo $lngp;

$json_url = 'http://overpass.osm.rambler.ru/cgi/interpreter';

$data = '<query type="way"> <bbox-query s="' . $lngm . '" w="' . $latm . '" n="' . $lngp . '" e="' . $latp . '"/> <!--this is auto-completed with the current map view coordinates.--> </query> <print/>';

$ch = curl_init( $json_url );

$options = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
);

curl_setopt_array($ch, $options);
$result =  curl_exec($ch);

$resultArr = explode("<",$result); //Array without "<" tags!

foreach ($resultArr as $val) {
    $temp = explode('"', $val); //Array without """ tags!
    //print_r ($temp);

//Trying to check if temp[1] is maxspeed, then get the value of temp[3]...
            if ($temp[1]=="maxspeed")
            $speedlimit=$temp[3];
    }
    echo $speedlimit;

    ?>

注:此处评论仅供核对...

我知道我犯了一些小错误,我希望有人能告诉我我做错了什么或指导我正确的方向!!

非常感谢!

问题是并非所有方式都包含名为 maxspeed 的标签,因此您还需要检查是否

isset($temp[1]) && $temp[1] == "maxspeed"

您还可以像这样使用 simplexml:

$xml = simplexml_load_string($result);

foreach ($xml->way as $i) {
    foreach ($i->tag as $tag) {
        if ($tag['k'] == "maxspeed") {
            $maxspeed = $tag['v'];
            break;
        }
    }
}

echo $maxspeed;

可能是语法错误? IF 语句缺少大括号?

if ($temp[1]=="maxspeed")
$speedlimit=$temp[3];

应该是:

if ($temp[1]=="maxspeed") {
$speedlimit=$temp[3];
}