1

I have a script that uses regex to get some value on a page retrieved with curl.

the code: preg_match('/<h2>([\d\,]+)<\/h2>/', $curl_exec, $matches);

When I print_r($matches) in my browser, it's always there.

I'm using this script in a cron job to get the results every 10 minutes. when I test it myself and use 'php script.php', it always says undefined index for the data i want to get, but if i do 'php script.php' a second time, it works. Does anyone know what could be causing this? Any work arounds?

$CurlHandle = curl_init($StatsUrl);
curl_setopt($CurlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($CurlHandle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($CurlHandle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0 Firefox/17.0");

$Data = curl_exec($CurlHandle);

preg_match("/<h2>([\d\,]+)<\/h2>/", $Data, $Matches);

print_r($Data);

if(!isset($Matches[1])) exit('Irrecoverable error.');

$PlayerCount = str_replace(",", "", $Matches[1]);

$CurrentTime = time();
Steve
  • 2,936
  • 5
  • 27
  • 38
  • Maybe my comment is kinda off-topic but I think it's useful. [Don't parse html with Regex, please](http://stackoverflow.com/a/1732454/1283847) – Leri Nov 07 '12 at 06:51
  • yeah, yeah I know. that doesn't really solve my problem as I've used a DOM parser (simplehtmldom) etc, and the same thing happens. – Steve Nov 07 '12 at 07:05
  • Try adding `print_r($curl_exec)` to see what you're getting back from cURL. – Barmar Nov 07 '12 at 07:05
  • Yeah, I just did that. It shows nothing, blank. If I do it again right after, it loads the expected page. I don't get it. I've reproduced this 10 times andit's always the same behavior. – Steve Nov 07 '12 at 07:06
  • @Steve Could you show more code? It's clear that problem is neither `preg_match`, not `print_r`. – Leri Nov 07 '12 at 07:21
  • added more code. the check for Matches[1] was added as i first started diagnosing the problem, not before. – Steve Nov 07 '12 at 07:25
  • possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Jocelyn Mar 29 '13 at 11:59

1 Answers1

0

Don't know what was originally causing the problem, but I added a system('php script.php'); in the event of failure, so it calls it twice. This is obviously a duct tape solution, but it's working.

Steve
  • 2,936
  • 5
  • 27
  • 38