Search code examples
phpforeachsearch-engine

How to use foreach statement to loop through Faroo json search engine results?


I do not quite understand the parameters I need to use for a foreach statement to work on this query.

Any idea why this foreach does not work? sample faroo query: http://www.faroo.com/api?q=%27elephants%27&start=1&length=10&l=en&src=web&f=json&jsoncallback=mycallback&key=y3EVs8B2ntbxXrmZWpBTDBueayA_&rlength=0

<?php

$ch = curl_init();

if ($_POST['query'])
{
    $query = urlencode("'{$_POST['query']}'");
    $fullUri = 'http://www.faroo.com/api?q='.$query.'&start=1&length=10&l=en&src=web&f=json&jsoncallback=mycallback&key=y3EVs8B2ntbxXrmZWpBTDBueayA_&rlength=0';
    curl_setopt($ch, CURLOPT_URL, $fullUri);
    echo $fullUri;
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    $data=curl_exec($ch);
    $js = json_decode($data);
    $i=0;
    foreach ($js -> results as $item)
    {
        $Faroo[$i] = "<a href=\"{$item->url}\"> 
        {$item->title}</a>faroo  
        <p>$item->kwic}</p>";    
        $i++;

    }

    echo $Faroo[3];

}

Solution

  • Remove the jsoncallback parameter from the request... what's being returned isn't valid JSON. Removing this parameter fixes the issue.

    I'd check into json_last_error if you run into issues with JSON in the future- it can be very helpful!