R
R
ree4i2015-04-25 10:53:11
PHP
ree4i, 2015-04-25 10:53:11

How to check simplexml_load_file for successful loading?

As a standard script I load xml from not the most stable server.

$linkxml="http://ссылка.ру";
$xml = simplexml_load_file($linkxml);

often the script produces a set of standard errors, such as:
Warning: simplexml_load_file() [function.simplexml-load-file]: http://ссылка.ру:6: parser error : Opening and ending tag mismatch: hr line 5 and body in /home/public_html/ссылка/update.php on line 106

Checking the server's response won't help. The server will answer "200", but the file will still not be loaded to the end.
How to do type checking correctly:
$linkxml="http://ссылка.ру";
$xml = simplexml_load_file($linkxml);
if (!simplexml_load_file($linkxml)) {echo 'файл не получен';} else {$xml = "не могу придумать как получить сюда данные из simplexml_load_file";}

And immediately the question is to catch up - how to restart the script in case of unsuccessful loading, or rather, how to do it more correctly than stupidly copying the entire parsing code from else to if?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gregory, 2015-04-25
@ree4i

The documentation says
And the warning that this occurs because of incorrect XML, which is what is written in the LOGS. In the code, check as follows: if ($xml !== false) {...}
If you return invalid XML, then this will not change over time (most likely), so restarting and further attempts to load will not lead to anything. And if you really want to try to download again, then try

do {
$xml = simplexml_load_file(...);
} while ($xml === false);
// $xml загружен.

Only in this form, be careful - it is very easy to get an infinite loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question