我在php中编写了以下代码,它使用json查找地点详细信息并且工作正常。
<?php
function search_place_details($location)
{
$locationclean = str_replace (" ", "+", $location);
$details_url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" . $locationclean . "&key=MY-GOOGLE-API-KEY";
$du = file_get_contents($details_url);
$getDetails = json_decode(utf8_encode($du),true);
if ($getDetails['status']=="OK")
{
$a = $getDetails['results'][0]['types'];
echo implode(" ",$a)."<br>";
}
else
{
echo "Place details not found";
}
}
search_place_details("kfc");
?>
但我想通过使用xml来做同样的事情。我的xml代码看起来像这样
<?php
function search_place_details($location)
{
$locationclean = str_replace (" ", "+", $location);
$data = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" . $locationclean . "&key=MY-GOOGLE-API-KEY";
$xml = file_get_contents($data);
$xml = simplexml_load_string($xml);
foreach($xml->result->type as $key => $value)
{
$location_details = $value;
echo $location_details;
echo "<br>";
}
}
search_place_details("kfc");
?>
两者都给出相同的结果,但我想让我的xml代码显示错误消息,如果找不到地方详细信息。 建议??
答案 0 :(得分:0)
您可以考虑以下选项:
选项1.从Xml结果中提取状态代码
$xml = simplexml_load_string($xml);
$statusCode = (string)$xml->status;
if($statusCode != "OK")
throw new Exception('Invalid request');
选项2.将Xml转换为Json并验证状态代码
$json = json_encode($xml);
$result = json_decode($json,TRUE);
$statusCode = $result['status'];
if($statusCode != "OK")
throw new Exception('Invalid request');