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;
Related
This question already has answers here:
PHP replace wildcards (%s, %d) in string with vars
(2 answers)
Closed 3 years ago.
I've got a JSON file which looks like this
{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}
So I'm getting users social links from a form, but only the user's ID of social link eg.https://facebook.com/ID. I'm storing the users ID in JSON file in database. I'm using PHP. How do I add the users ID in that '%s' and display the link.
To put together the information using the JSON data you have, you would use either sprintf() or printf() (the only difference being the printf() directly outputs the data sprintf() returns a string). The information on the manual pages shows how things like %s works.
So the code would look something like...
$id = 123;
$userName = "User name";
$json = '{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}';
$socialMedia = json_decode( $json, true );
echo echo '<a href="'.sprintf($socialMedia["facebook"]["url"], $id).'">'.
$userName.'</a>';
Which outputs...
User name
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.
I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.
I'm using php to decode dailymotion api for related videos but my code is not working.. If i replace "list" with any other word it works perfectly.. But i have to use the word list due to dailymotion api.. Anyone who can help?
$string='{"list":[
{
"duration": 233,
"id": "x2laq9v",
"thumbnail_480_url": "http://s1.dmcdn.net/JsC-U/x480-8Xl.jpg",
"title": "Heart Touch Mashup 2015 | Hindi latest Sad Songs | Very Sad Song"
},
{
"duration": 239,
"id": "x2laq9v",
"thumbnail_480_url": "http://s1.dmcdn.net/JsC-U/x480-8Xl.jpg",
"title": "title 2"
}
]}';
$json_a=json_decode($string,true);
// array method
foreach($json_a[list] as $p)
{
echo '
duration: '.$p[duration].'
<br>title: '.$p[title].'
<br><br>';
}
You have decoded the JSON string as an associative array. You need to access the elements by giving the key as a string. Otherwise, PHP will assume it as a constant.
So, change
foreach($json_a[list] as $p)
{
echo '
duration: '.$p[duration].'
<br>title: '.$p[title].'
<br><br>';
}
to
foreach($json_a["list"] as $p)
{
echo '
duration: '.$p["duration"].'
<br>title: '.$p["title"].'
<br><br>';
}
It should work fine, then.
Try to put quotes on the array :
foreach($json_a['list'] as $p)
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'];