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.
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:
I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.
I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2
My code:
$json_response = json_decode($response, true);
$tag= $json_response['results']['tags'][0]['tag'];
print $tag;
My JSON:
{
"results": [
{
"tagging_id": null,
"image": "image.jpg",
"tags": [
{
"confidence": 100,
"tag": "herb"
},
{
"confidence": 98.3637619018555,
"tag": "plant"
}
]
}
]
}
I am trying to output "herb". I have looked up through examples but cannot figure out where the bug is.
I am reading results and then the trees.
You have to fetch the first element inside ['results'].
echo $json_response['results'][0]['tags'][0]['tag'];
I've this JSON string:
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
}
}';
I'd like to print every single entry on a webpage using php and then save these entries on a mysql db.
In the db there is already a "code", "name" and "link" field..
This is what I've tried without luck (to print the stuff on a page):
$obj = json_decode($json,true);
echo ($obj["bigprodlist"]["prods"][0]["name"]);
Thank you very much for the help
First, fix your JSON missing end bracket that makes JSON decoding fail (add the ] after the prods data ), then expand your echo statement with some foreach loops to get the data printed. This is only a simple example to get you on the right track:
foreach ($obj["bigprodlist"]["prods"] as $p):
echo "<div>";
foreach ($p as $name=>$value):
echo "<span>".$name.": ".$value."</span>";
endforeach;
echo "</div>";
endforeach;
You can then use the same loop procedure to get the data into your DB.
You need to use json_last_error(); http://no1.php.net/manual/en/function.json-last-error.php
Debugging:
$obj = json_decode($json,true);
var_dump($obj, json_last_error());
You are missing a ] :
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
] //missing!
}
}';
Where did you get json output?
It's invalid:
Parse error on line 18:
... } } }
----------------------^
Expecting ',', ']'
Check your json at http://jsonlint.com/