Harinarayan Harinarayan - 1 month ago 6
jQuery Question

why i am getting Cannot redeclare httpGet() error

Below is the code in which I am getting error:

for ($i = 0, $count = count($arr1); $i < $count; $i++)
{
print $arr1[$i]."\n\r\n\r\n\r\n\r<br/><br/><br/>";
$_SESSION['arrayvalue'] = "$arr1[$i]";
$in = $arr1[$i];
$in = str_replace(' ','+',$in); // space is a +
//google site search start here
function httpGet($url15)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url15);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
// curl_setopt($ch,CURLOPT_HEADER, false);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}

$result15 = httpGet("https://www.google.com/cse?cx=003255331468891741234:xxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
echo $result15;
//this is to get perticular tag/node value
$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($result15);
$N = $dom->getElementsByTagName('U');
foreach ($N as $U) {
echo $U->nodeValue, PHP_EOL."<br/>";
}
}


This is the error which I am getting after showing one result:

Fatal error: Cannot redeclare httpGet() (previously declared in
/home/checkforplag/public_html/test/index.php:352) in
/home/checkforplag/public_html/test/index.php on line 352

Answer

This issue is happening because you're trying to define the function httpGet multiple times (It's within the loop). Simply removing it to the outside, will define the function and allow it to be used later in the script. See also this answer.

//google site search start here
function httpGet($url15)
{
   $ch = curl_init();  
   curl_setopt($ch,CURLOPT_URL,$url15);
   curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
   //  curl_setopt($ch,CURLOPT_HEADER, false); 
   $output=curl_exec($ch);
   curl_close($ch);
   return $output;
}

for ($i = 0, $count = count($arr1); $i < $count; $i++) 
{
   print $arr1[$i]."\n\r\n\r\n\r\n\r<br/><br/><br/>";
   $_SESSION['arrayvalue'] = "$arr1[$i]";
   $in = $arr1[$i];
   $in = str_replace(' ','+',$in); // space is a +

   $result15 = httpGet("https://www.google.com/cse?cx=003255331468891741234:xxxxxxxxx&client=google-csbe&output=xml_no_dtd&q='.$in.'&oq='.$in.'");
   echo $result15;
   //this is to get perticular tag/node value 
   $dom = new DomDocument;
   $dom->preserveWhiteSpace = FALSE;
   $dom->loadXML($result15);
   $N = $dom->getElementsByTagName('U');
   foreach ($N as $U) {
      echo $U->nodeValue, PHP_EOL."<br/>";
   }
}

Another alternative is to wrap your function in an if statement to see if the function already exists:

if ( !function_exists('httpGet') )
{
    function httpGet($url15)
    {
        //Function code here
    }
}
Comments