2013-07-17 96 views
1

我非常感谢您对此的帮助。 基本上,我有一个PHP网页,用户在其中选择一个城市名称(通过其代码),然后将其发送到脚本,该脚本在数据库中查找城市,获取与其关联的XML文件,其中包含其当前天气,然后显示它。 除非用户选择一个不存在的代码,否则它一切正常。那么,什么情况是,我得到的消息:XML解析器错误处理

Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 1: parser error : Start tag expected, '<' not found in ... 

与存在的主要问题是,它停止所有负载,这样不仅用户看到这一点,而且,页面的其余部分,包括HTML和一切都没有加载。

我想要的是一些检查,如果文件没有找到有错误的结构,只是回应一些消息,如“错误,未找到城市”,并跳过脚本的其余部分,但加载网页的其余部分,其HTML等。

我在互联网上找到了一些解决方案,但我无法成功实现它。

加载实际的XML代码看起来是这样的:

public function __construct($query, $units = 'imperial', $lang = 'en', $appid = ''){ 

$xml = new SimpleXMLElement(OpenWeatherMap::getRawData($query, $units, $lang, $appid, 'xml')); 

$this->city = new _City($xml->city['id'], 
$xml->city['name'], 
$xml->city->coord['lon'], 
$xml->city->coord['lat'], 
$xml->city->country); 

etc. 

如果这个城市是找不到的,而不是XML,程序获取此:

http://api.openweathermap.org/data/2.5/weather?id=123456

万一它被发现,它得到这个:

http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml

回答

0

根据SimpleXMLElement的文档,如果文件无法解析,构造函数将抛出异常。我会尝试在一个try-catch包裹它:

try { 
    $xml = new SimpleXMLElement(...); 
    // The xml loaded, so display the proper information. 
} catch (Exception $e) { 
    // If it gets here, the xml could not load, so print your 'city not found' message and continue loading the page. 
} 

什么情况是,它将尝试建立一个新的SimpleXMLElement对象,但构造函数将“扔”的错误。通常情况下,投掷会阻止一切事物的发展,但是由于你在“捕捉”它,所以你明确地说:“嘿,如果有问题,将控制权交还给我,让我决定如何处理”。