Newbie PHP question here:
I am using the Vimeo API to access video information and am using PHP to receive the initial array of data. I know how to access the data by using calls like:
echo $array['body']['description'];
But I need to access data like this where 'download' would be accessed via
echo $array['body']['download'];
Specifically where the quality is stated as source as I don't need the other ones. From it I need the link.
"download": [
{
"quality": "mobile",
"type": "video/mp4",
"width": 480,
"height": 270,
"expires": "2015-01-07T18:51:48+00:00",
"link": "LINK",
"created_time": "2015-01-02T18:47:11+00:00"
},
{
"quality": "source",
"type": "source",
"width": 1920,
"height": 1080,
"expires": "2015-01-07T18:51:48+00:00",
"link": "LINK",
"created_time": "2015-01-02T18:25:19+00:00"
}
]
Thank you all for your help!
You can loop through the array $array['body']['download'] then check the value of quality. If it equals source then get the link.
foreach( $array['body']['download'] as $innerArray ){
if( $innerArray['quality'] === 'source' ){
echo $innerArray['link'];
}
}
If you want to filter an array by properties within the array, you can use array_filter with your own filter callable. In your case, try:
$downloads = array_filter($array['body']['download'], function($download) {
return $download['quality'] === 'source';
});
Some like
$arr = $array['body']['download'];
$link = '';
for($i = 0; $i <count($arr); $i ++ ){
if(#$arr[$i]['quality'] == 'source') {
$link = #arr[$i]['link'];
break;
}
}
echo $link;
Related
I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:
This is my data and i want to print the value using decode Json data into array value so please help me out.
{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/",
},
"liked": false
} ] }
I want to retrieve total_results and photos->src->original so how can i do?
First you'll need to use json_decode to converts it into a PHP object:
$response = json_decode($url);
To retrieve total_results:
echo $response->total_results;
You'll have to loop through photos attribute since it's an array of objects:
foreach ($response->photos as $photo) {
echo $photo->src->original;
}
If you have only one object of photos then you can do as below
$obj = '{
"total_results": 10000,
"page": 1,
"per_page": 15,
"photos": [
{
"id": 1687093,
"width": 3079,
"height": 4619,
"url": "https://fingerprintdesigns.studio/",
"photographer": "Cameron Casey",
"photographer_id": 455136,
"src": {
"original": "https://fingerprintdesigns.studio/"
},
"liked": false
} ] }';
// Convert JSON string to Array
$objectArray = json_decode( $obj, true );
print_r($objectArray); // Dump all data of the Array
echo $total_results = $objectArray['total_results']; // Access Array data
echo $originalPhoto = $objectArray['photos'][0]['src']['original'];
// For multiple value
if( is_array( $objectArray['photos'] ) && !empty( $objectArray['photos'] ) ){
foreach ($objectArray['photos'] as $photo) {
echo $photo['src']['original'];
}
}
I'm trying to use JSON in PHP and I got stucked. I'm new in this, please, if you can help me with that.
I want to display content from "list" from the code below (For example list, name and/or frags).
{
"status": true,
"hostname": "{IP}",
"port": {PORT},
"queryPort": {PORT},
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}
This is the code I use (Doesn't work):
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
} else {
echo $info['players']['list']['name'];
}
?>
Thanks in advance,
Jim.
$info['players']['list'][0]['name']
This will get you desired element. Try outputting $info next time to find this error yourself.
Try using a foreach loop. It's cleaner when iterating an array.
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
}
else {
foreach ($info['players']['list'] as $player) {
echo $player['name'];
}
}
?>
list will you number of online users records so there may be single or multiple users so you have to go through the loop and can display all the records available in the list. Add for loop to your code instead of displaying single record with index.
if(count($info['players']['list']) > 0){
for($cnt = 0; $cnt < count($info['players']['list']); $cnt++){
echo $info['players']['list'][$cnt]['name'];
}
} else {
echo "Write your message";
}
Took the following array (I had to change few things) and go here . Paste the array at the left side, then press the right arrow and see at the right side the analysis of your array. Open the tree view and you will realize that there is a 0 index in the list. So you can not access what you want by doing echo $info['players']['list']['name']; but you need to apply the index 0 of the list echo $info['players']['list'][0]['name'];
[{
"status": true,
"hostname": "{IP}",
"port": 555,
"queryPort": 555,
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}]
If you paste your json string into https://jsonlint.com/ and click Validate JSON, you will see that you have a couple of syntax errors; namely the values for port and queryPort.
When they are corrected, you should have something like this:
{
"status": true,
"hostname": "{IP}",
"port": "{PORT}",
"queryPort": "{PORT}",
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}]
},
"cached": false
}
Now that the json is fixed, you can convert it to an array for simple processing.
Code: (Demo)
$serverip="localhost";
$array=json_decode(file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip),true);
if(!isset($array['status']) || $array['status']===false){
echo 'Offline';
}else{
foreach($array['players']['list'] as $players){
echo "<div>Name: {$players['name']}, Frags: {$players['frags']}, Ping: {$players['ping']}</div>\n";
}
}
foreach() is a better/cleaner practice than resorting to for() which will unfortunately require count(), and a "counter" variable, and incrementation.
I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.
You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);
In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);
I've been dealing with this problem around 5 hours, so I think that's time to ask here.
I'm retrieving data using Facebook Graph API and using JSON decoding to put it all together on a PHP.
Here's FB Graph:
{
"feed": {
"data": [
{
"message": "A file.",
"id": "831407506978898_831408573645458",
"attachments": {
"data": [
{
"target": {
"id": "1041214692589250",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
},
"title": "Clase 01 - Vías de administración.pdf",
"type": "file_upload",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"message": "A photo.",
"id": "831407506978898_831408496978799",
"attachments": {
"data": [
{
"description": "A photo.",
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838160017396",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"id": "831407506978898_831408450312137",
"attachments": {
"data": [
{
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838168217601",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"message": "TEST",
"id": "831407506978898_831407576978891"
},
{
"id": "831407506978898_831407516978897"
}
],
"paging": {
"previous": "https://graph.facebook.com/...alotofjunk"
}
},
"id": "0000000000000"
}
And my PHP is the following one:
<?php
header('Content-Type: text/html; charset=utf-8');
$limit = 60; // The number of posts fetched
$access_token='TOKEN NUMBER';
$group_id = 'GROUPNUMBER';
$url1 = 'https://graph.facebook.com/'.$group_id.'?access_token='.$access_token;
$des = json_decode(file_get_contents($url1)) ;
$url2 = "https://graph.facebook.com/{$group_id}/feed?access_token={$access_token}";
$data = json_decode(file_get_contents($url2));
?>
<?
$counter = 0;
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
<? $themessage = (isset($d->message) ? $d->message : false); ?>
<? print $themessage ?>
<? $thepicture = (isset($d->picture) ? $d->picture : false); ?>
<? print "<img src=\"$thepicture\">" ?>
<!--THE PROBLEM IS FROM HERE.... -->
<?
$counter = 0;
foreach($d->attachments->data as $d2) {
if($counter==$limit)
break;
?>
<? $attachments = (isset($d2->url) ? $d2->url : false); ?>
<? print $attachments ?>
<?
}
?>
<!-- ...TO HERE -->
<?
$counter++;
}
?>
I get a perfect output of $themessage and $thepicture, but I with $attachments I receive the following errors:
Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
I've already read this: Trouble with Facebook multi-level json php foreach loop, but no luck.
How can I fix this?. Thanks a lot!
You need to be careful when you're chaining objects - especially in loops. One empty object will bring down the whole show. Try this:
$counter = 0;
if( isset( $d->attachments ) )
{
foreach( $d->attachments->data as $d2 )
{
....
}
}
Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
You're getting this error becoz you're missing feed object in your first loop
HereDEMO
Replace
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
With
foreach($data->feed->data as $d) {
if($counter==$limit)
break;
?>
Your JSON is in this format paste your JSON here JSON Format Viewer and check it
I tried your code i'm able to get url printed HereDEMO
$data="Your JSON Here"
foreach($data->feed->data as $d) {
$themessage = (isset($d->message) ? $d->message : false);
print("\n".$themessage);
$thepicture = (isset($d->picture) ? $d->picture : false);
print("\n<img src='$thepicture'>");
foreach($d->attachments->data as $d2) {
$attachments = (isset($d2->url) ? $d2->url : false);
print("\n".$attachments);
}
}
Side Note: you're initailising $counter = 0; twice once inside loop
and outside the loop its bad Even for $attachment, Its my opinion after looking your code for first time whatever you're reason be behind it