Search code examples
phpcurldomdocumentsimple-html-dom

PHP curl for data from website returning empty arrays


I am trying to write a Php Script to pull snow and other data from www.snowbird.com/mountain-report/ to display via an led array. I am having troubles with getting the data I need. I can't seem to be able to find a way to make it work. Would I be able to make this work, or would I have to go about and use a different language?

The following code only return empty. Following the code I will post what is returned.

<?php
require('simple_html_dom.php');

$ch = curl_init("http://www.snowbird.com/mountain-report/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

$html = new simple_html_dom(); 
$html->load($content);

$ret1 = $html->find('.snowfall-total');
print_r ($ret1);
$ret2 = $html->find('#twenty-four-hour');
print_r ($ret2);
$ret3 = $html->find('#forty-eight-hour');
print_r ($ret3);
$ret4 = $html->find('#current-depth');
print_r ($ret4);
$ret5 = $html->find('#year-to-date');
print_r ($ret5);
?>

Here is the output

pi@KPi /var/www $php test4.php

Array
(
)
Array
(
)
Array
(
)
Array
(
)
Array
(
)

Solution

  • The website you are trying to request from throws an error when using cURL because the google tools they have implemented in their python code crash when there is no user agent set.

    Try adding this line to your code before curl_exec($ch)

    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    And as @jeroen said, using json_decode($content, true) is not neccesary as the returned data will be HTML code not a json string. Remove that line as well and you should be good to go.