简体   繁体   中英

Iterate over a JSON response and get results into variables

I am trying to build a simple script that I can pass in a list of Twitter username and it will then access the Twitter API and returns a list of details for the user's that I requested.

Below is what I have so far, it returns a JSON response with all the data for the 3 user's that I sent in the URL.

I need to figure out how to access each of these items, I plan to save them to a database so I need to be able to access the returned items as a variable. Also the number of users/results in the JSON will be different each time depending on how many names I request so I need to somehow iterate over this JSON response.

Can anyone help me?

$json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');

$obj = json_decode($json);
echo '<pre>';
print_r($obj);
echo '</pre>';

Iterating is easy:

foreach ($obj as $varName => $varValue)
{
   // ...
}

Use foreach to iterate over the JSON object.

    $json = file_get_contents('http://api.twitter.com/1/users/lookup.json?screen_name=fishriver,metinogtem,friendproject');
    $obj = json_decode($json);
    echo '<pre>';
    foreach($obj as $index => $user) {
        echo $user->screen_name."<br>";
        // insert into database here
    }
    echo '</pre>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM