parsing - XML parser error handling -


i appreciate this. basically, have php webpage, user chooses city name (by code) , sent script, finds city in database, gets xml file associated it, contains current weather, , displays it. works fine except when user selects code, not exist. happens message:

warning: simplexmlelement::__construct() [simplexmlelement.--construct]: entity: line 1: parser error : start tag expected, '<' not found in ... 

the major problem is, stops loading, not user see this, also, rest of page including html , not loaded.

what have sort of check, in case file not found has wrong structure, echoes message "error, city not found" , skips rest of script, loads rest of webpage, html etc.

i found solutions on internet not able implement successfully.

the code loads actual xml looks this:

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. 

in case city not found, instead of xml, program gets this:

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

in case found, gets this:

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

according documentation of simplexmlelement, constructor throw exception if file not parsed. try wrapping in try-catch:

try {   $xml = new simplexmlelement(...);   // xml loaded, display proper information. } catch (exception $e) {   // if gets here, xml not load, print 'city not found' message , continue loading page. } 

what happens is, attempt construct new simplexmlelement object, constructor 'throw' error. throw stop in tracks, since 'catching' it, explicitly saying, "hey, if there problem, return control me , let me decide it".


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -