How to extract json_decode array element value from cURL - php

What I am trying to do is to get the value of the first element, [0]['uri'] from my result curl api. I have an associative array from the curl_exec but can't figure out how to extract the data to find the value of the first element. I have tried echo $alerts[0]['uri'] but it doesn't work.
<?php
// Initiate curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json',"Authorization: Bearer $access_token"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$alerts = json_decode($result,true);
print_r($alerts);
//echo $alerts[0]['uri'] doesn't work.
?>
Output Result:
Array (
[result] => success
[message] => Array (
[alerts] => Array (
[0] => Array (
[id] => 78591963
[uri] => htps://access.rrr.com/interface/open_api/api/alerts/78591963
)
[1] => Array (
[id] => 78576283
[uri] => htps://access.rrr.com/interface/open_api/api/alerts/78576283
)
[2] => Array (
[id] => 78576209
[uri] => htps://access.rrr.com/interface/open_api/api/alerts/78576209
)
[3] => Array (
[id] => 78572644
[uri] => htps://access.rrr.com/interface/open_api/api/alerts/78572644
)
[4] => Array
)
)
)
)

Answer was given by other gentlemen in the comment.
I failed to look at the array structure. It is simply:
$alerts['message']['alerts'][0]['uri']

Related

How to print following json data using foreach in php(coinmarket api)

I am trying to print the following json data in foreach loop of php. Can anyone please tell me how I can do it? I have searched a lot but nothing works.
I am getting this data from coinmarket api and printing this code by using:
but failed to get every value separately.
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
print_r(json_decode($response));
Below is code that I want to use in foreach loop:
stdClass Object ( [status] => stdClass Object ( [timestamp] => 2019-10-09T03:13:30.051Z [error_code] => 0 [error_message] => [elapsed] => 9 [credit_count] => 1 [notice] => ) [data] => stdClass Object ( [BTC] => stdClass Object ( [id] => 1 [name] => Bitcoin [symbol] => BTC [slug] => bitcoin [num_market_pairs] => 7935 [date_added] => 2013-04-28T00:00:00.000Z [tags] => Array ( [0] => mineable ) [max_supply] => 21000000 [circulating_supply] => 17981825 [total_supply] => 17981825 [platform] => [cmc_rank] => 1 [last_updated] => 2019-10-09T03:12:33.000Z [quote] => stdClass Object ( [USD] => stdClass Object ( [price] => 8195.0290967 [volume_24h] => 14981665979.667 [percent_change_1h] => -0.224992 [percent_change_24h] => -1.35388 [percent_change_7d] => -1.38135 [market_cap] => 147361579086.77 [last_updated] => 2019-10-09T03:12:33.000Z ) ) ) ) )
Please format your question, code and output so it's becomming readable. What have you tried yet? What data do you need?
To get a list of the names of all coins retrieved in data you can use this code:
$response = json_decode($response);
foreach ($response->data as $coin){ // assuming the data could contain multiple coins
echo $coin->name;
echo '<br>';
}
Tip: if you want to see a nice formatted output of print_r() in an HTML-page you can place it between PRE-tags.
echo '<pre>';
print_r($my_object);
echo '</pre>';

php Curl iterate through json decoded array

I have a problem with a json decoded array using cURL. I am gathering data from Leadfeeder to get recent companies that visited our site. I have a custom start and end date and I wish to return all the companies that visited in the day. I can do this but it returns a json array. I am only able to access one company. However I need to access the entire array
below is an example of the code
$url = "https://api.leadfeeder.com/accounts/youraccount/visits?start_date=".date("2018-02-04")."&end_date=".date("Y-m-d").""; // Captcha plugin url
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Authorization: Token token=Token-here'));
$result = (string)curl_exec($ch);
echo "<pre>";
$leadfeeder = json_decode($result, true);
#$lead_id = $leadfeeder['data'][1]['attributes']['lead_id'];
foreach ($leadfeeder as $r) {
echo $r['data'];
}
When I run the above I get the following error
Notice: Undefined index: data in /opt/lampp/htdocs/leadfeeder.php on
line 28
Notice: Undefined index: data in /opt/lampp/htdocs/leadfeeder.php on
line 28
This is an example of the output
Array
(
[data] => Array
(
[0] => Array
(
[id] => 86b8e468-0af7-11e8-8738-11129da81150
[type] => visits
[attributes] => Array
(
[source] => en.wikipedia.org
[medium] => referral
[referring_url] =>
[page_depth] => 1
[visit_route] => Array
(
[0] => Array
(
[hostname] =>
[page_path] => /
[previous_page_path] => (entrance)
[time_on_page] => 0
[page_title] =>
[page_url] =>
[display_page_name] =>
)
)
[keyword] =>
[visit_length] => 0
[started_at] => 2018-02-05T23:51:00.000Z
[date] => 2018-02-05
[hour] => 23
[lead_id] => 02e01b12-2c9b-11e5-b645-3df00765f195_uM2sktjSDJNrnkRHg49WRe
)
)

Getting wrong number of results in youtube API php

I am trying to fetch videos from youtube using below code:
$youtube_api_url = "https://www.googleapis.com/youtube/v3/search?key=".$new_key->api_key;
$youtube_api_url = $youtube_api_url."&order=relevance&type=video&maxResults=20&part=snippet&videoCategoryId=10&q=". urlencode(preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '',$trackRecord->name));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$youtube_api_url);
$result=curl_exec($ch);
$response = json_decode($result, true);
echo "<pre>"; print_r($response); die;
It is returning wrong number of results as below:
Array
(
[items] => Array
(
[0] => Array
(
[kind] => youtube#searchResult
[etag] => "m2yskBQFythfE4irbTIeOgYYfBU/ne5AZXpdoLtAn-mlwu4ipioOQ_I"
[id] => Array
(
[kind] => youtube#video
[videoId] => dB0ITzfbwfw
)
[snippet] => Array
(
[publishedAt] => 2017-01-23T17:31:23.000Z
[channelId] => UCdW5nPo1oyD2vLkvoYijmEg
[title] => Lihtz Kamraz "The Switch Up" Interview Part 2
[description] => In 2016, a lot of break out artists emerged and made a mark in the game. As 2017 begins, one name that you should definitely be on the lookout for is Lihtz ...
[thumbnails] => Array
(
[default] => Array
(
[url] => https://i.ytimg.com/vi/dB0ITzfbwfw/default.jpg
[width] => 120
[height] => 90
)
[medium] => Array
(
[url] => https://i.ytimg.com/vi/dB0ITzfbwfw/mqdefault.jpg
[width] => 320
[height] => 180
)
[high] => Array
(
[url] => https://i.ytimg.com/vi/dB0ITzfbwfw/hqdefault.jpg
[width] => 480
[height] => 360
)
)
[channelTitle] => HIPHOPSINCE1987TV
[liveBroadcastContent] => none
)
)
)
)
As you can see it is showing total and per page result as:
[pageInfo] => Array
(
[totalResults] => 14
[resultsPerPage] => 20
)
How can I get all results?

print encoded or decoded json in readable format

I am using php curl to get account and transaction data from the plaid api. I'd like to see it in a nice format so I can go about creating loops to save the information into a database. The decoded json output, when printed with print_r, is returned like this:
array ( [accounts] => Array ( [0] => Array ( [_id] => QPO8Jo8vdDHMepg41PBwckXm4KdK1yUdmXOwK [_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA [_user] => eJXpMzpR65FP4RYno6rzuA7OZjd9n3Hna0RYa [balance] => Array ( [available] => 1203.42 [current] => 1274.93 ) [institution_type] => fake_institution [meta] => Array ( [name] => Plaid Savings [number] => 9606 ) [subtype] => savings [type] => depository ) [1] => Array ( [_id] => nban4wnPKEtnmEpaKzbYFYQvA7D7pnCaeDBMy [_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA...
I'd like to get it looking like this:
Array (
[accounts] => Array (
[0] => Array (
[_id] => QPO8Jo8vdDHMepg41PBwckXm4KdK1yUdmXOwK
[_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA
[_user] => eJXpMzpR65FP4RYno6rzuA7OZjd9n3Hna0RYa
[balance] => Array (
[available] => 1203.42
[current] => 1274.93 )
[institution_type] => fake_institution
[meta] => Array (
[name] => Plaid Savings
[number] => 9606 )
[subtype] => savings
[type] => depository )
[1] => Array (
[_id] => nban4wnPKEtnmEpaKzbYFYQvA7D7pnCaeDBMy
[_item] => KdDjmojBERUKx3JkDd9RuxA5EvejA4SENO4AA
`
For reference, here is the code to get the response:
$data = array(
"client_id"=>"test_id",
"secret"=>"test_secret",
"access_token"=>"test_chase"
);
$string = http_build_query($data);
//initialize session
$ch=curl_init("https://tartan.plaid.com/connect/get");
//set options
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute session
$accountData = json_decode(curl_exec($ch), true);
print_r($accountData);
//close session
curl_close($ch);
Any thoughts other than loops?

How do I get the Array total for stdClass Object?

I am trying to get the total for the Array in the Object.
I am using print_r to get the following to see whats in it.
stdClass Object ( [data] => Array ( [0] => stdClass Object ( [name] => The Drift Bible [category] => Movie [id] => 227431881228 [created_time] => 2011-02-27T21:41:04+0000 ) [1] => stdClass Object ( [name] => Shooter [category] => Movie [id] => 109671005718938 [created_time] => 2011-02-16T09:18:29+0000 ) [2] => stdClass Object ( [name] => Tron [category] => Movie [id] => 99792857339 [created_time] => 2010-11-29T03:18:06+0000 ))
here is my code to get the information
$movies = json_decode(file_get_contents('https://graph.facebook.com/me/movies?'
.'format=json&access_token=' . $session['access_token']));
Again I just need to get the Array value. Such as 3 in the about example above.
I am very new to this. Any advice will help.
Thanks
Try:
$c = count($movies->data)
//creating facebook_id from facebook_url
$sRequestUrl = 'http://graph'.strstr($a_data['contact_data']['facebook'], '.facebook');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $sRequestUrl
));
$res = curl_exec($curl);
curl_close($curl);
$res = json_decode($res);
id = $res->id;
about = $res->about;
just call the name of the variable key

Categories