0

I have this notice:

Notice: Undefined offset: 1 in D:\serveurs\data\localweb\alexa traffic.php on line 14

the line 14 is this:

$usrank = ($rankus[1]) ? $rankus[1] : 0;

How do I fix this?

Here is my code:

<?php
$source = file_get_contents('http://data.alexa.com/data?cli=10&dat=snbamz&url=linuxplained.com');

//Alexa Rank
preg_match('/\<popularity url\="(.*?)" text\="([0-9]+)" source\="panel"\/\>/si', $source, $matches);
$aresult = ($matches[2]) ? $matches[2] : 0;

//Alexa Sites Linking in
preg_match('/\<linksin num\="([0-9]+)"\/\>/si', $source, $asli);
$alinksin = ($asli[1]) ? $asli[1] : 0;

//Alexa US Rank
preg_match('/\<country code\="US" name\="United States" rank\="([0-9]+)"\/\>/si', $source, $rankus);
$usrank = ($rankus[1]) ? $rankus[1] : 0;

//Alexa Reach Rank
preg_match('/\<reach rank\="([0-9]+)"\/\>/si', $source, $reachr);
$areach = ($reachr[1]) ? $reachr[1] : 0;
?>
user229044
  • 232,980
  • 40
  • 330
  • 338
user38867
  • 7
  • 2
  • Weird that that this isn't in the [error reference wiki](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – John Conde May 20 '14 at 18:05

2 Answers2

3

Use isset() to check to see if that value exists:

$usrank = (isset($rankus[1])) ? $rankus[1] : 0;
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • I am assuming if they wrote it that way, they understand how it is used. Might be a big assumption but one I'm willing to make. – John Conde May 20 '14 at 18:16
0

This error occurs because the array $rankus doesn't have a value at index 1. The easiest fix is by using isset to check whether the index exists before attempting to use it. So then your could would be:

$usrank = (isset($rankus[1])) ? $rankus[1] : 0;

This uses the ternary operator, which is equivalent to the following (easier to understand) code:

$usrank;
if (isset($rankus[1]) {
    $usrank = $rankus[1];
} else {
    $usrank = 0;
}

Hopefully you now understand why the problem occurs and how to fix this.

There are more problems in your code though. When you create the variables $aresult, $alinksin and $areach, you don't check whether the needed indexes exist either. You should probably do this in order to avoid more errors like the one you get at the moment.

Finally, I noticed you are trying to parse an XML document using regular expressions. That can go wrong in a lot of ways, and it's better to use a 'real' XML parser. Take a look at SimpleXML or one of the other XML libraries for PHP!

Frog
  • 1,631
  • 2
  • 17
  • 26