Multitasking/Multithreading

Hello,
I’m dealing with this for the first time so I’m not sure how to implement it.
So I receive data via XML feed from URL and my code right now looks like this:

$products_url = ‘here comes URL to XML’;
$products = DcXmlToArray($products_url);
if(isset($products[‘product’]) && !empty($products[‘product’])) {

foreach($products[‘product’] as $key => $product) {

  $img_url = 'another URL for images...'; 
  $images = DcXmlToArray($img_url);
           foreach($images['image'] as $image) {
              //doing some work in here
            }

}

function DcXmlToArray looks like this:

function DcXmlToArray($url) {
$xml = simplexml_load_file($url, ‘SimpleXMLElement’,LIBXML_NOCDATA);
$json = json_encode($xml);
$arr = json_decode($json,true);
return $arr;
}

And it all works very slowly (especially because of this URL with images) and I contacted support and there they told me to try multithreadingand they gave me this link:

But I’m not sure how to implement this into my code.
If someone can help me, I would be grateful.
Thanks.

Multitasking can be complicated to implement, and doesn’t always help. Whenever you have a performance problem, your first task should be to “profile” your code or find exactly where it is spending the most time. the more involved way to do this would be to install and use something like Xdebug to profile your code - among other things, Xdebug can record a timeline of your process and show where it spends the most time.

A simpler but less detailed way is to simply add debug statements in your script that print out the system time. either

echo microtime();

to print to your output, or

file_put_contents('mylogfile.log', microtime() . PHP_EOL, FILE_APPEND);

to log them to a file. If you add these statements throughout your code, you can narrow down where your code is slow by watching for big jumps in the time between statements.

Once you’ve found precisely where your code is slow you can start to improve it; this may lead you towards multitasking, but there are other approaches depending on exactly what the problem is. Your best bet is to narrow down what code is causing the problem first, then asking again.

Sponsor our Newsletter | Privacy Policy | Terms of Service