Drilling down into JSON with PHP - php

This is a really simple task, that has me absolutely stumped! I'm pulling back some JSON via CURL and PHP, and attempting to access the data from the below structure:
object(stdClass)[1]
public 'maxResults' => int 43
public 'resultList' =>
array (size=43)
0 =>
object(stdClass)[2]
public '#class' => string '' (length=64)
public 'id' => int
public 'version' => int 0
public 'dateCreated' => string '2014-02-11T18:37:55.835+0000' (length=28)
public 'dateModified' => null
public 'locationId' => int
public 'departmentId' => int
public 'ownerCompanyId' => int
public 'active' => boolean true
public 'userId' => int
public 'userName' => string '' (length=24)
public 'externalCode' => null
public 'employeeDetails' =>
object(stdClass)[3]
...
public 'chargeBandAllocationsIds' =>
array (size=7)
...
public 'personalRateChargeBandId' =>
object(stdClass)[13]
...
public 'employeeGroupIds' =>
array (size=0)
...
public 'isResource' => boolean false
(I've removed some of the values, for privacy reasons)
Now I'm trying to var_dump using var_dump(json_decode($result, false));, however when I try and get into the 'resultList' array using var_dump(json_decode($result['resultList'], false)); I get an illegal string offset error.

$result is the JSON string, your cannot do $result['resultList'] on a string. It only becomes a structure after you json_decode it. However, you're decoding it as object, not array, so this wouldn't work either way.
$data = json_decode($result);
var_dump($data->resultList);
var_dump($data->resultList[0]);
var_dump($data->resultList[0]->id);
foreach ($data->resultList as $employee) {
var_dump($employee->id);
}

Related

Google MyBusiness API PHP Locations

its my first Google MyBusiness API encounter.
Im trying to retrieve account locations but ive got nothing.
I dont have direct access for account, my client gave me access to API by json file.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/plus.business.manage');
$service = new Google_Service_MyBusiness($client);
$accounts = $service->accounts->listAccounts();
and i don't have any error, just Google_Service_MyBusiness_ListAccountsResponse object, then giving foreach on that object and I can get account informations:
object(Google_Service_MyBusiness_Account)[94]
protected 'internal_gapi_mappings' =>
array (size=0)
empty
public 'accountName' => null
public 'accountNumber' => null
public 'name' => string 'accounts/XXXXXXXXXXXXXXXXXXXXX' (length=30)
protected 'organizationInfoType' => string 'Google_Service_MyBusiness_OrganizationInfo' (length=42)
protected 'organizationInfoDataType' => string '' (length=0)
public 'permissionLevel' => null
public 'profilePhotoUrl' => string '.../photo.jpg' (length=94)
public 'role' => null
protected 'stateType' => string 'Google_Service_MyBusiness_AccountState' (length=38)
protected 'stateDataType' => string '' (length=0)
public 'type' => string 'PERSONAL' (length=8)
protected 'modelData' =>
array (size=0)
empty
protected 'processed' =>
array (size=0)
empty
public 'state' =>
object(Google_Service_MyBusiness_AccountState)[84]
protected 'internal_gapi_mappings' =>
array (size=0)
empty
public 'status' => string 'UNVERIFIED' (length=10)
protected 'modelData' =>
array (size=0)
empty
protected 'processed' =>
array (size=0)
empty
Now when i try:
$name = $account->getName(); //accounts/XXXXXXXXXXXXXXXXXXXXX
$service->accounts_locations->listAccountsLocations($name);
i get almost empty Google_Service_MyBusiness_ListLocationsResponse object:
object(Google_Service_MyBusiness_ListLocationsResponse)[88]
protected 'collection_key' => string 'locations' (length=9)
protected 'internal_gapi_mappings' =>
array (size=0)
empty
protected 'locationsType' => string 'Google_Service_MyBusiness_Location' (length=34)
protected 'locationsDataType' => string 'array' (length=5)
public 'nextPageToken' => null
public 'totalSize' => null
protected 'modelData' =>
array (size=0)
empty
protected 'processed' =>
array (size=0)
empty
What is wrong? Am I doing something wrong, or i have wrong credentials(?). How can I check/ask client that he gave me correct access. Can he check Account name in his panel or something?
You appear to be trying to use a service account. As per the doucmentation Basic setup you need to create an Oauth2 client and use that to login to an account that has access to the my business account.
Service accounts do not appear to be supported by Google MyBusiness API as per the documentation.

PHP undefined property in Twitter response

I have a problem with accessing one of the properties in stdClass returned from Twitter api, I'm trying to get property named extended_entities however PHP constantly returns error complaining that the property doesn't exist. I can clearly see it thoug in var_dump. See output:
object(stdClass)[597]
public 'created_at' => string 'Mon Mar 23 16:39:25 +0000 2015' (length=30)
public 'id' => int 580046201061580800
public 'id_str' => string '580046201061580800' (length=18)
...
public 'user' =>
object(stdClass)[600]
...
...
public 'notifications' => boolean false
public 'geo' => null
...
public 'entities' =>
object(stdClass)[581]
public 'hashtags' =>
array (size=0)
empty
public 'symbols' =>
array (size=0)
empty
public 'user_mentions' =>
array (size=0)
empty
public 'urls' =>
array (size=0)
empty
public 'media' =>
array (size=1)
0 =>
object(stdClass)[593]
...
public 'extended_entities' =>
object(stdClass)[573]
public 'media' =>
array (size=2)
0 =>
object(stdClass)[556]
...
1 =>
object(stdClass)[595]
...
public 'favorited' => boolean false
public 'retweeted' => boolean false
public 'possibly_sensitive' => boolean false
public 'possibly_sensitive_appealable' => boolean false
public 'lang' => string 'en' (length=2)
I have no problem getting property for example retweeted, created_at etc. in the following way:
$response->retweeted //this returns false
$response->user //returns stdClass
however
$response->extended_entities
or
$response->extended_entities->media
returns
Notice: Undefined property: stdClass::$extended_entities
I expect to have object or array respectively. I don't understand why I can access some of the properties and this one not?

Ajax between two PHP scripts

I'm tring to perform an AJAX request between 2 PHP scripts, one of them just returns (echoes) some data in the form of a json string:
[{'foo':'bar'}]
And the other one just makes a simple http request to it:
$c = new http\Client;
$r = new http\Client\Request('GET', 'http://example.com/script.php');
$c->enqueue($r,
function(http\Client\Response $r) {
// Do something with the Json here.
return true;
})->send();
But I just can't figure out how to get that Json string from the Response object. PECL's documentation doesn't help at all:
<?php
$request = new http\Client\Request("GET",
"http://example.com",
["User-Agent"=>"My Client/0.1"]
);
$request->setOptions(["timeout"=>1]);
$client = new http\Client;
$client->enqueue($request)->send();
// pop the last retrieved response
$response = $client->getResponse();
printf("%s returned '%s' (%d)\n",
$response->getTransferInfo("effective_url"),
$response->getInfo(),
$response->getResponseCode()
);
?>
This just yields:
http://example.com/ returned 'HTTP/1.1 200 OK' (200)
But nothing more. How can I do this?
Update:
This is a dump of the Response object using var_dump.
object(http\Client\Response)[6]
protected 'type' => int 2
protected 'body' =>
object(http\Message\Body)[5]
protected 'requestMethod' => string '' (length=0)
protected 'requestUrl' => string '' (length=0)
protected 'responseStatus' => string 'OK' (length=2)
protected 'responseCode' => int 200
protected 'httpVersion' => string '1.1' (length=3)
protected 'headers' =>
array (size=7)
'Server' => string 'nginx/1.4.7' (length=11)
'Date' => string 'Sat, 20 Dec 2014 23:20:07 GMT' (length=29)
'Content-Type' => string 'text/html' (length=9)
'Connection' => string 'keep-alive' (length=10)
'X-Powered-By' => string 'PHP/5.5.19' (length=10)
'X-Original-Transfer-Encoding' => string 'chunked' (length=7)
'Content-Length' => int 1695
protected 'parentMessage' =>
object(http\Client\Request)[3]
protected 'type' => int 1
protected 'body' =>
object(http\Message\Body)[8]
protected 'requestMethod' => string 'GET' (length=3)
protected 'requestUrl' => string 'http://localhost/battleturnrest/work.GetTop50.php' (length=49)
protected 'responseStatus' => string '' (length=0)
protected 'responseCode' => int 0
protected 'httpVersion' => string '1.1' (length=3)
protected 'headers' =>
array (size=0)
empty
protected 'parentMessage' => null
protected 'options' => null
protected 'transferInfo' =>
object(stdClass)[7]
public 'effective_url' => string 'http://localhost/battleturnrest/work.GetTop50.php' (length=49)
public 'response_code' => int 200
public 'total_time' => float 0.01084
public 'namelookup_time' => float 0.000913
public 'connect_time' => float 0.001345
public 'pretransfer_time' => float 0.002432
public 'size_upload' => float 0
public 'size_download' => float 1695
public 'speed_download' => float 156365
public 'speed_upload' => float 0
public 'header_size' => int 180
public 'request_size' => int 135
public 'ssl_verifyresult' => int 0
public 'filetime' => int -1
public 'content_length_download' => float -1
public 'content_length_upload' => float 0
public 'starttransfer_time' => float 0.010685
public 'content_type' => string 'text/html' (length=9)
public 'redirect_time' => float 0
public 'redirect_count' => int 0
public 'connect_code' => int 0
public 'httpauth_avail' => int 0
public 'proxyauth_avail' => int 0
public 'os_errno' => int 111
public 'num_connects' => int 1
public 'ssl_engines' =>
array (size=0)
empty
public 'cookies' =>
array (size=0)
empty
public 'redirect_url' => string '' (length=0)
public 'primary_ip' => string '127.0.0.1' (length=9)
public 'appconnect_time' => float 0
public 'condition_unmet' => int 0
public 'primary_port' => int 80
public 'local_ip' => string '127.0.0.1' (length=9)
public 'local_port' => int 45915
public 'curlcode' => int 0
public 'error' => string '' (length=0)
This is exactly the same call-request scenario. The main.php calls answer.php, and it answers with json.
answer.php
<?php
// the json header
header('Content-Type: application/json');
// parameter "value" from URL http://.../answer.php?value=bar
$value = $_REQUEST["value"];
// returns exactly [{'foo':'bar'}]
echo(json_encode(array(array("foo" => $value))));
?>
main.php
<?php
...
$bar = "bar";
$url = "http://.../answer.php?value=" . $bar;
$arr = json_decode(file_get_contents($url));
...
>
The most important thing is main.php executes line by line and you can not send two or more calls to the answer.php in the same moment.
But if:
main.php
<?php
// the crucial difference: asynchronous calls to the answer.php
class Ask_For_Value extends Thread {
public function __construct($value, $func){
$this->val = $value;
$this->func = $func;
}
function start(){
$arr = json_decode(file_get_contents("http://.../answer.php?value=" . $this->val));
call_user_func($this->func, $arr);
return(0);// boolean "OK"
}
}
// function to process the result
function do_some_thihg_with_the_result(&$array){...}
// prepare the threads
$call1 = new Ask_For_Value("bar_1", "do_some_thihg_with_the_result");
$call2 = new Ask_For_Value("bar_2", "do_some_thihg_with_the_result");
$call3 = new Ask_For_Value("bar_3", "do_some_thihg_with_the_result");
// start the threads
$call1->start();
$call2->start();
$call3->start();
// there is nothing happens, because the threads
// will continue execution asynchronous and
// independent in the "function do_some_thihg_with_the_result()"
?>

Laravel -Strange Behaivor. Controller data and Blade data

I am returning a value from a variable in my controller but it yields different results when I dd($roles) in my blade view.
public function index()
{
$users = $this->user->getAll(); //DBUserRepository
$roles = $this->user->getRoles($users)
return $roles;
}
Yields correct results
{
id: "1",
username: "Muzikman",
email: "matt.paolini#gmail.com",
password: "$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG",
password_confirmation: "",
confirmation_code: "91f0583ed76c95ebf378648d65d0eac7",
remember_token: "bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle",
confirmed: "1",
created_at: "2014-10-19 12:17:55",
updated_at: "2014-10-20 15:07:01",
roles: [
{
id: "12",
name: "Members",
created_at: "2014-10-24 20:45:26",
updated_at: "2014-10-24 20:45:26",
}
]
However, when return $roles from controller to blade it yields different results.
public function index() { $users = $this->user->getAll(); $roles = $this->user->getRoles($users);
return View::view('admin.index', compact('users'))->withRoles($roles); }
Blade var dump {{ dd($roles) }} returns
array (size=2)
0 =>
object(User)[254]
protected 'connection' => null
protected 'table' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=10)
'id' => string '1' (length=1)
'username' => string 'Muzikman' (length=8)
'email' => string 'matt.paolini#gmail.com' (length=22)
'password' => string '$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG'
'password_confirmation' => string '' (length=0)
'confirmation_code' => string '91f0583ed76c95ebf378648d65d0eac7' (length=32)
'remember_token' => string 'bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle' (
'confirmed' => string '1' (length=1)
'created_at' => string '2014-10-19 12:17:55' (length=19)
'updated_at' => string '2014-10-20 15:07:01' (length=19)
protected 'original' =>
array (size=10)
'id' => string '1' (length=1)
'username' => string 'Muzikman' (length=8)
'email' => string 'matt.paolini#gmail.com' (length=22)
'password' => string '$2y$10$Sp7k9Fs0DwFSYHTpWrTWquFmXJpkiKfRIHsjYtdEXTvbdOJwv9AtG'
'password_confirmation' => string '' (length=0)
'confirmation_code' => string '91f0583ed76c95ebf378648d65d0eac7' (length=32)
'remember_token' => string 'bGmdTchXtilBj41FIazkFS3PDZzr1tVKmTFnMkeeSoD7wpW6hoQ07A42plle' (length=60)
'confirmed' => string '1' (length=1)
'created_at' => string '2014-10-19 12:17:55' (length=19)
'updated_at' => string '2014-10-20 15:07:01' (length=19)
protected 'relations' =>
array (size=1)
Can someone explain what is going on here? Sending the same data object to blade from the controller with different array contents.
Here is the code from my interface:
public function getRoles($users)
{
foreach($users as $user){
$roles[] = \User::with('roles')->find($user->id);
}
return $roles;
}
dd($roles) will spit out the object itself, as see in the second set of output.
{{ $roles }} is going to spit out the object having been run through its toJson() function, resulting in your first set of output.
in this code
public function index()
{
$users = $this->user->getAll(); //DBUserRepository
$roles = $this->user->getRoles($users)
return $roles;
}
you did not dump it, you return the $roles, i think, when you return something and the content is "JSONable", laravel will set the appropriate header and convert the content to JSON. (found in Illuminate\Http\Response)
while the other one
{{ dd($roles) }}
it is same with
<?php var_dump($roles); ?>
which in PHP says that the said function displays structured information about one or more expressions that includes its type and value.
I am just curious. If you are just getting 'roles' column by ::with('roles') function. Why did other info come up in your dd() function result?

return all the array between one hour via php

lets say we do some search useing search api then it retuns something like this in json.
'results' =>
array
0 =>
object(stdClass)[9]
public 'from_user_id_str' => string '57393273' (length=8)
public 'profile_image_url' => string 'http://a1.twimg.com/profile_images/1150792547/49146_1365401218_7951632_q_normal.jpg' (length=83)
public 'created_at' => string 'Mon, 06 Jun 2011 04:01:36 +0000' (length=31)
public 'from_user' => string 'primalokomotif' (length=14)
public 'id_str' => string '77585906684526592' (length=17)
public 'metadata' =>
object(stdClass)[10]
public 'result_type' => string 'recent' (length=6)
public 'to_user_id' => null
public 'text' => string 'RT #detikcom kober siap perkenalkan ajaran klub suami suami takut istri' (length=71)
public 'id' => float 7.7585906684527E+16
public 'from_user_id' => int 57393273
public 'geo' => null
public 'iso_language_code' => string 'id' (length=2)
public 'to_user_id_str' => null
public 'source' => string '<a href="http://mobile.twitter.com" rel="nofollow">Mobile Web</a>' (length=97)
1 =>
object(stdClass)[11]
public 'from_user_id_str' => string '278060132' (length=9)
public 'profile_image_url' => string 'http://a1.twimg.com/profile_images/1355377589/296218442_normal.jpg' (length=66)
public 'created_at' => string 'Mon, 06 Jun 2011 04:01:34 +0000' (length=31)
public 'from_user' => string 'kaka_kecil' (length=10)
public 'id_str' => string '77585897637412864' (length=17)
public 'metadata' =>
object(stdClass)[12]
public 'result_type' => string 'recent' (length=6)
public 'to_user_id' => null
public 'text' => string 'RT #detikcom: 'Milan Tak Pernah Inginkan Hamsik' http://de.tk/dP7Cs via #detiksport' (length=83)
public 'id' => float 7.7585897637413E+16
public 'from_user_id' => int 278060132
public 'geo' => null
public 'iso_language_code' => string 'id' (length=2)
public 'to_user_id_str' => null
public 'source' => string '<a href="http://ubersocial.com" rel="nofollow">ÃœberSocial</a>' (length=94)
2 =>
object(stdClass)[13]
public 'from_user_id_str' => string '185984810' (length=9)
public 'profile_image_url' => string 'http://a0.twimg.com/profile_images/1368466468/a_normal.jpg' (length=58)
public 'created_at' => string 'Mon, 06 Jun 2011 04:01:31 +0000' (length=31)
public 'from_user' => string 'tiayeeeaah' (length=10)
public 'id_str' => string '77585887143276544' (length=17)
public 'metadata' =>
object(stdClass)[14]
public 'result_type' => string 'recent' (length=6)
public 'to_user_id' => null
public 'text' => string 'hmm..hmm.. -___-" RT #detikcom: Bandung Siap Perkenalkan Ajaran Klub Istri Taat Suami http://bit.ly/kCcOsG' (length=111)
public 'id' => float 7.7585887143277E+16
public 'from_user_id' => int 185984810
public 'geo' => null
public 'iso_language_code' => string 'id' (length=2)
public 'to_user_id_str' => null
public 'source' => string '<a href="http://seesmic.com/seesmic_desktop/sd2" rel="nofollow">Seesmic Desktop</a>' (length=115)
3 => etc
how can we return arrays that have date less then one hour ? or filter it? maybe something like do a search then returns all the array that have strtotime(created_at) < strtotime("+1 Hours")
*edit
like How can I use the Twitter Search API to return all tweets that match my search query, posted only within the last five seconds?
but there is no answer doing this.
thanks for looking in
Adam Ramadhan
So, you're looking to return only those that have created_at within the past hour? I like to use array_filter() when I can.
function filterWithinHour($obj)
{
return (strtotime($obj->created_at) > strtotime('-1 hour'));
}
$recent = array_filter($results, 'filterWithinHour');
If you ever need need to pass it a certain time (instead of assuming now), you might want to just loop through the array manually rather than mess with trying to pass a time parameter to the callback with a global variable. I hate globals used like that.
The Twitter Search API has a since_id that could help you:
Returns results with an ID greater
than (that is, more recent than) the
specified ID. There are limits to the
number of Tweets which can be accessed
through the API. If the limit of
Tweets has occured since the since_id,
the since_id will be forced to the
oldest ID available.
If you poll every hour, you effectively get the posts of the last hour. If the service is down, you still won't miss any tweets since you could go back several days.

Categories