php执行停止了simplexml_load_string()错误

时间:2012-08-23 08:12:23

标签: php

我有这个PHP脚本从谷歌API加载谷歌天气。

<?php

      //Weather Forecast icon and temperature from google weather API

      $setYourLanguage = "en"; // Possibilities: "en" - english; "ru" - russian; "ka" - georgian;
      //WEATHER, read google XML weather forecast
      $URL = "http://www.google.com/ig/api?weather=".$myCity."&hl=".$setYourLanguage."";

      $dataInISO = file_get_contents($URL);
      $dataInUTF = mb_convert_encoding($dataInISO, "UTF-8", "ISO-8859-2"); //fix Google's API UTF-8 bug
      $xml = simplexml_load_string($dataInUTF); 

      $current = $xml->xpath("/xml_api_reply/weather/current_conditions");
      $iconData = str_replace("/ig/images/weather/", "weather/",  $current[0]->icon['data']);
      $iconData = str_replace(".gif", ".png", $iconData);

?>

但有时页面无法加载,我在apache2日志中出错:

[Thu Aug 23 12:04:16 2012] [error] [client ::1] PHP Warning:  simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/homepage-structure.php on line 23
[Thu Aug 23 12:04:16 2012] [error] [client ::1] PHP Warning:  simplexml_load_string(): Unsupported API in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/homepage-structure.php on line 23
[Thu Aug 23 12:04:16 2012] [error] [client ::1] PHP Warning:  simplexml_load_string(): ^ in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/homepage-structure.php on line 23
[Thu Aug 23 12:04:16 2012] [error] [client ::1] PHP Fatal error:  Call to a member function xpath() on a non-object in /Library/WebServer/Documents/wordpress/wp-content/themes/directorypress/homepage-structure.php on line 25
[Thu Aug 23 12:05:57 2012] [error] [client ::1] What

为什么会发生这种情况?我的理论是它无法正确连接到URL并以这种方式失败...但为什么页面加载停止了?有什么办法可以避免这个错误吗?并允许页面完全加载?

1 个答案:

答案 0 :(得分:1)

如果SimpleXml无法加载XML,则变量$xml的值为false,而不是SimpleXMLElement类型的实例。也就是说,错误信息说的是什么:

  

[Thu Aug 23 12:04:16 2012] [error] [client :: 1] PHP致命错误:在/ Library / WebServer / Documents / wordpress /中的非对象上调用成员函数xpath()第25行的wp-content / themes / directorypress / homepage-structure.php

因此,在访问对象上的函数之前,应该检查它。

if ($xml) {
      $current = $xml->xpath("/xml_api_reply/weather/current_conditions");
      $iconData = str_replace("/ig/images/weather/", "weather/",  $current[0]->icon['data']);
      $iconData = str_replace(".gif", ".png", $iconData);
}

然后,即使来自Web服务的XML加载失败,您的页面也会完全加载。