views:

72

answers:

1
<?php
//example code
$url = 'http://clients1.google.com/complete/search?hl=en&amp;q=speed';
function processURL( $url )
{
    $contents = file_get_contents( $url );
    return $contents;
}
print_r( processURL($url) );

?>

Output:

window.google.ac.h(["speed",[["speed test","89,300,000 results","0"],["speed channel","76,100,000 results","1"],["speed of light","120,000,000 results","2"],["speed test speakeasy","362,000 results","3"],["speedfan","1,660,000 results","4"],["speed of sound","83,200,000 results","5"],["speedy rewards","2,790,000 results","6"],["speedo","6,580,000 results","7"],["speedway","12,800,000 results","8"],["speedway motors","486,000 results","9"]]])

example output of what I want:

out[0].word['speed test'];
out[0].results['89,300,000'];
out[1].word['speed channel'];
out[1].results['76,100,000'];
out[2].word['speed of light'];
out[2].results['120,000,000'];

etc...

Thanks for any help.

+1  A: 

The return is supposed to be passed to a Javascript method. So before you can use json_decode you have to strip that away. After that, its a simple loop through the results to reformat how you want the array to be set up:

$in = processURL($url);

# Strip away non JSON parts
$in = substr( trim($in), 19, -1);

# Decode JSON
$results = json_decode( $in );

# New array that will hold your new format
$formatted_results = array();
foreach($results[1] as $result){
    $formatted_results[] = array(
        "word" => $result[0],
        "results" => preg_replace('/ results?$/i', '', $result[1])
    );
}

# Use formatted_results to access as you desired

echo $formatted_results[0]['word']; # speed test
echo $formatted_results[0]['results']; # 89,300,000

My code includes no error handling other than the possibility of it saying 1 result instead of always using the plural. But it should point you in the right direction.

Doug Neiner
Thank you for this...
Brad
No problem! Glad I could help.
Doug Neiner