Peter Kazazes
Peter Kazazes

Reputation: 3628

Decoding only one key of Twitter's JSON in PHP and putting it in an array

Using Twitter's search API, I'm being returned a helluva lot of information that is essentially extraneous to me. I'd like to populate an array with just the content of the tweets, none of the metadata.

Here's an example of a request and the response. So basically, I'd like to populate an array with the values of the text key.

I assume the answer would like in some kind of for loop however I don't know where to begin.

Upvotes: 0

Views: 810

Answers (2)

Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

try this:

Convert JSON to Array PHP

<?php
    //get json
    $foo= file_get_contents('http://search.twitter.com/search.json?q=stackoverflow&rpp=10&result_type=recent&lang=en');

    //convert to array
    $var = json_decode( $foo , true );

    //print array
    print_r( $var );
?>

Convert Array PHP to JSON

<?php
    //declarate array
    $foo = array( 1 ,2 ,3 ,4 ,5 , 6 => 7, 8);

    //convert to json
    $var = json_encode( $foo );

    //print json
    print_r( $var );
?>

Read:

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

See And Read This JSON PHP Documentation

AND

If you use PHP < 5.2, use JSON Class Objects

Bye!

Upvotes: 0

glortho
glortho

Reputation: 13200

Something like this will do it:

<?
    $json = json_decode(file_get_contents('http://search.twitter.com/search.json?q=laughter&rpp=100&result_type=recent&lang=en'));
    $l = count($json->results);
    for ($i=0; $i < $l; $i++) { 
        echo $json->results[$i]->text . '<br/>';
    }
?>

Note: Use whatever reading method you need if file_get_contents isn't allowed to read remote.

Upvotes: 1

Related Questions