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>';
Related
I am attempting to extract JSON values from the return of a JWTAuth token 'user' key but cannot figure out how to address the inner keys using php. I have the following code:
if(!$user = JWTAuth::parseToken()->authenticate()){
abort(401);
}
else{
return response()->json(compact('user'));
}
}
And when including the proper token in the header, I do receive the user info
{"user":{"id":2,"organization_name":"test corp","user_type":"administrator","created_at":"2016-05-13 17:26:20","updated_at":"2016-05-13 17:26:20","user_firstname":"Requester","user_lastname":"chester","user_emailaddress":"requester#test.com","remember_token":null,"user_id":"uid-7e3a0e15-c97b-44b1-885d-4370f4d1"}}
However, I cannot figure out a way to address the individual values of the keys inside of the "user" key. How can I get the value of say the "user_firstname" key?
Thanks.
UPDATE
Using the Log::Info function within laravel to log data a local log. The following:
$json = response()->json(compact('user'));
$arr = json_decode($json, true);
Log::Info(var_dump($arr));
Log::Info($arr["user"]["user_firstname"]);
returns NULL for both the var dump and the multidimensional array call
You might want to learn about json_encode and json_decode to convert json objects into an array and vice versa. See manual here - http://php.net/manual/en/function.json-decode.php
$array = json_decode($json, true);
var_dump($array);
echo $array["user"]["user_firstname"];
$json = '{"user":{"id":2,"organization_name":"test corp","user_type":"administrator","created_at":"2016-05-13 17:26:20","updated_at":"2016-05-13 17:26:20","user_firstname":"Requester","user_lastname":"chester","user_emailaddress":"requester#test.com","remember_token":null,"user_id":"uid-7e3a0e15-c97b-44b1-885d-4370f4d1"}}';
$arr = json_decode($json, true); //Converts JSON string into array
echo "<pre>";
print_r($arr);
echo "<pre>";
You could access array value :
echo $arr["user"]["user_firstname"]; //Prints Requester
I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];
below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];
I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);
http://developers.facebook.com/docs/reference/api/event
I'm trying to grab some values from a Facebook JSON even object in PHP. Namely, title of event, location, and people attending. Using the Graph API.
<?php
$jsonurl = "https://graph.facebook.com/331218348435?access_token=2227470867|2.rtBZMkVIVgKGZ7Xr4px3Dw__.3600.1280822400-662817093|apY_UHK_2SKQFel3XxpKJ09GEo4.";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
How can echo the values from JSON output? I'm assuming it will be returned as an array.
Thank you!
If you're using PHP, you can use the PHP SDK to query the API. This means you can make calls like:
$user = $facebook->api('/someusername', array('fields' => 'id,first name,last_name ...'));
However, with your example, you could do the following:
$url = "https://graph.facebook.com/331218348435?access_token=2227470867|2.rtBZMkVIVgKGZ7Xr4px3Dw__.3600.1280822400-662817093|apY_UHK_2SKQFel3XxpKJ09GEo4.";
$user = json_decode(file_get_contents($jsonurl));
echo $user['first_name'];
As if you use json_decode, it should decode the result into a native PHP array (or in same cases, an object).
Specify the second argument of true to json_encode to convert it to array and then you can print the output like this:
$json_output = json_decode($json, true);
echo '<pre>';
print_r($json_output);
echo '</pre>';
Now you can get specific item like this:
echo $json_output['title'];