Answer the question
In order to leave comments, you need to log in
How to stop php loop on time?
The while loop is executed
Inside it is $object=simplexml_load_file($i);
where $i=" site.ru/file.xml "
sometimes the site blunts and does not return xml and the script freezes.
How to reveal it? Is it possible to stop the loop if it "hangs" for N seconds?
Answer the question
In order to leave comments, you need to log in
Divide the task into simple steps. So that at each step you can catch errors and process them:
only by script timeout php.net/manual/ru/function.set-time-limit.php
or like this:
function simplexml_load_file_from_url($url, $timeout = 5){
$context = array('http' => array('timeout' => (int)$timeout));
$data = file_get_contents($url, false, $context);
if(!$data){
trigger_error('Cannot load data from url: ' . $url, E_USER_NOTICE);
return false;
}
return simplexml_load_string($data);
}
If this is a sitemap, break it into several parts
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://site.com/sitemap/part1.xml</loc>
</sitemap>
<sitemap>
<loc>http://site.com/sitemap/part2.xml</loc>
</sitemap>
</sitemapindex>
It's better to use XmlReader to traverse the tree structure and simplexml to read nodes so you can read large xml without the need for memory consuming script.
(In practice, I used it when parsing YML product catalogs of 2GB + file, the average value of memory consumption is 16-17MB.)
XmlReader reads the document on the fly without loading the tree into the operative
simplexml reads the file into the operative then parses ...
function getSimpleXMLInstance($xml_reader)
{
$doc = new DOMDocument('1.0', 'UTF-8');
return simplexml_import_dom($doc->importNode($xml_reader->expand(), true));
}
//....
$xml_reader = new XMLReader();
$reader = $xml_reader;
$reader->open($catalog->yml_catalog_url)
while ($reader->read())
{
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'sitemap')
{
try
{
// тут simplexml
$simpleXmlObject = getSimpleXMLInstance($reader);
}
catch (Exception $e)
{
continue;
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question