JSON Extracting Data Into Variable Using PHP - php

I'm using a YouTube data API request to grab the channel id, but i'm not too sure why it isn't working:
The returned JSON request i'm getting is:
{
"kind": "youtube#channelListResponse",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/k5qSWj-xcF96jAN3p1uQH1amSRc\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/e1xTbLf6JLhwwzeWbdMfWdPfcwg\"",
"id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw"
}
]
}
To extract the JSON data i'm using the a few lines of code and a function in php:
$banner_data = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&forUsername=pewdiepie&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY');
$banner_data = json_decode($banner_data, true);
$YTid = $banner_data['items']['id'];
When i :
echo "YouTube Channel Id Of pewdiepie is " . $YTid . ".<br />";
I don't get the channel id? What's my problem?

Items is an array containing one or more objects. So it has to be:
$YTid = $banner_data['items'][0]->id;
This way you grab 'id' from the first item in the items-array.
BTW: learning to debug is crucial to learning to code. If you decode the json and then print the outcome you can see the structure of the array, which could have helped you to find the problem, like:
$banner_data = json_decode($banner_data, true);
var_dump($banner_data);

Try this instead:
$YTid = $banner_data['items'][0]['id'];

Related

PHP Only Getting First Page of JSON Result

I am receiving JSON that looks like this:
{
"result": "SUCCESS",
"message": {
"totalResults": 371711,
"resultsPerPage": 25,
"page": 1,
"data": [
{
"orderId": "8A62D2C05A",
"clientOrderId": "8A62D2C05A",
"shipCarrier": null,
"shipMethod": null,
"dateCreated": "2019-01-01 00:01:14",
"dateUpdated": "2019-01-27 10:44:57",
"orderType": "NEW_SALE",
"orderStatus": "COMPLETE",
"reviewStatus": "APPROVED",
"totalAmount": "9.93",
"avsResponse": null,
But I only get the 1st page of results, 25 items, with this code:
// curl stuff here
$rawresponse = curl_exec($curlSession);
$jrsp=json_decode($rawresponse,TRUE);
$result=$jrsp["result"];
$order_ct=$jrsp["message"]["totalResults"];
echo "Status $result for $order_ct orders.\n";
for ($i=0; $i<$order_ct; $i++) {
$cust_id=$jrsp["message"]["data"][$i]["customerId"];
$name=$jrsp["message"]["data"][$i]["name"];
$ord_dt=$jrsp["message"]["data"][$i]["dateCreated"];
$phone=$jrsp["message"]["data"][$i]["phoneNumber"];
$ord_amnt=$jrsp["message"]["data"][$i]["totalAmount"];
$item_ct=count($jrsp["message"]["data"][$i]["items"]);
echo "ID:$cust_id Name: $name Date:$ord_dt Phone:$phone Amnt: $ord_amnt Item:$item_ct\n";
}
All of the initial echo says, "Status: SUCCESS for 371711 orders." as expected, but I only get the first 25 data items. What do I need to do to get the other pages?
There is no "page" parameter in the api docs for the request, but I just found out from support the docs are incomplete. Jonnix and Barmar are both right. Thanks. I do need a for $pages loop to get all results.

Unable to fetch desired data from Google api through json_decode in PHP

I am unable to fetch desired data of title, score from the json_decode array, I have tried all the ways which are already discussed in stackoverflow. Can anyone help me..
$myKEY = "xyz";
$url_req= 'google api request here';
$results= checkPageSpeed($url_req_d);
$googleapi = json_decode($results,true);
Google api send the data like this when var_dump($googleapi) and I need to fetch title and score values from the array. Please reply suggested code to extract title and score values i.e "xyz" and "73"
{
"kind": "pagespeedonline#result",
"id": "www xyz com/",
"responseCode": 200,
"title": "xyz",
"ruleGroups": {
"SPEED": {
"score": 73
}
},
"pageStats": {
"numberResources": 67,
"numberHosts": 15,
"totalRequestBytes": "9354",
"numberStaticResources": 48,
"htmlResponseBytes": "129210",
"textResponseBytes": "5647",
"cssResponseBytes": "142839",
"imageResponseBytes": "411466",
"javascriptResponseBytes": "635453",
"otherResponseBytes": "94639",
"numberJsResources": 17,
"numberCssResources": 6
}, .........
$googleapi['title'] and $googleapi['ruleGroups']['SPEED']['score'] should do the trick. Check the documentation for more information on how you can access elements from multidimensional arrays.

creating json object from sql database using php

I am trying to create a json object from my mysql database for a android project. I need an output something like this:
{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://api.androidhive.info/feed/img/time.png",
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"
}
]
}
But I am getting ouput something like this:
{"feed":[{"id":"0","name":"punith","image":"","status":"ucfyfcyfffffffffffffffffffffffffffffffff","profilePic":"http:\/\/api.androidhive.info\/feed\/img\/nat.jpg","timestamp":"1403375851930","url":""}]}
Everything is on a single line and the id attribute should not be quotes. Is there anything I could do.This is my php file
<?php
define('HOST','');
define('USER','');
define('PASS','');
define('DB','');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from timeline";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'image'=>$row[2],
'status'=>$row[3],
'profilePic'=>$row[4],
'timestamp'=>$row[5],
'url'=>$row[6]
));
}
echo json_encode(array("feed"=>$result));
mysqli_close($con);
?>
And will it affect if the output is on a single line.
The database contains exactly the same columns used as attributes.
Thanks in advance
ID in quotes
ID is in quotes because it is a string, not an integer. You can change that by changing this:
array('id'=>$row[0]
to this:
array('id'=>intval($row[0])
"Pretty Printing"
Putting it on multiple lines will only affect readability but not how the data is computed - but you can prettify it: Pretty-Printing JSON with PHP
$output = json_encode(array("feed"=>$result), JSON_PRETTY_PRINT);
echo $output;
Try encoding with JSON_PRETTY_PRINT
$json_string = json_encode($data, JSON_PRETTY_PRINT);
where data is your result array.
in your case
echo json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
refer this Tutorial from the official PHP docs .
Aswell as the other answers, it would be more semantic to include the json header, I've found that just including this also helps with the appearance of the json itself so that it is formatted properly and not all one continuous string.
header('Content-Type: application/json');
For php>5.4
$json=json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);

How to get data in Json url using PHP [duplicate]

This question already has an answer here:
How to detect if content wasn't found in the feed URL using SimpleXML and PHP
(1 answer)
Closed 7 years ago.
So I have a URL that outputs as follows:
{
"kind": "youtube#channelListResponse",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/cElfTza4UGHG8g6mYtCKSIOXxq0\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/EGw-f95GMJ7EnCAhVPMzL1JSykQ\"",
"id": "UCxAICW_LdkfFYwTqTHHE0vg",
"statistics": {
"viewCount": "107418936",
"commentCount": "295",
"subscriberCount": "428265",
"hiddenSubscriberCount": false,
"videoCount": "2270"
}
}
]
}
I use this function to get the kind
function test() {
$url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=youtube&key={key}";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo $json_data["kind"];
}
But my issue is that I need to get other data including viewCount but I can't find a function for it..
Forgive me, I just started learning Json because i had to since YouTube API v 2 was deprecated and I had to switch to v 3.0 which relies on Json..
Thank you so much for assisting a beginner !
in simple way
echo $json_data["items"][0]['statistics']["viewCount"]; //107418936
echo $json_data["items"][0]['statistics']["commentCount"];// 259
It will return mixed format of array and object.
you can get view count like this.
echo $json_data->items[0]->statistics;
echo $json_data->items[0]->statistics->viewCount;

how to remove "result": "success" on json callback

The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.

Categories