Insert JSON values in MYSQL using PHP - php

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/

Related

Generate dynamic html with JSON output (with php)

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:

Getting data from nested arrays in json with php

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

Get JSon child with PHP echo from an API

Okay so bascially I have this structure as JSon from an API:
{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
},
I'm trying to get the Clan -> Name but it isn't working with this code in PHP:
echo "<p style='font-size:75;'>".$json->clan['name']."</p>";
How could I make it work?
Try this:
$json->clan->name
<?php
$json = '{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
}
}';
$json = json_decode($json);
echo $json->clan->name;
// Reddit Bravo
If you want to use $json['clan']['name']; then you have to set the assoc param like:
$json = json_decode($json, true);
echo $json['clan']['name'];
// Reddit Bravo
Depending on your particular call to json_decode(), if you've used...
$json = json_decode($jsonData,true);
then use
echo "<p style='font-size:75;'>".$json['clan']['name']."</p>";
Else if you've used...
$json = json_decode($jsonData);
then use
echo "<p style='font-size:75;'>".$json->clan->name."</p>";
If using the first call, then you create an associative array and so use array access method. If you don't pass true as the second parameter, this creates the structure as objects and so use the second method of access.
You will have to json_decode the same and use it.
Following is the piece of code
echo json_decode($json)->clan->name;
Stitch it into your HTML as
echo "<p style='font-size:75;'>".json_decode($json)->clan->name."</p>";
Tested this snippet. Should work for you too.

Can't display JSON Data in PHP

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.

How to extract Open Graph info from TXT file?

I have a TXT file containing some facebook Open Graph info like this:
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
In PHP, I want to extract all the id numbers from the rows that show
"id": "XXXXXXXXXXXX",
The output should look like this:
I like 8277564344063
I like 243564344063
I started the following but I am getting an error:
<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();
$text = file_get_contents('raw.txt');
$decode = json_decode($text);
print_r($decode);
$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);
fclose($file_handle);
?>
The error is that my output is blank! What am I doing wrong?
Please help?
You don't have valid JSON.
The JSON Object below this line is valid JSON. I removed the comma after your last associative array within your "data" array. You shouldn't need a comma at the end of the array.
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
Parse error on line 14:
... }, ], "paging": {
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As I removed the comma from the non-valid JSON. I was able to get the result you wanted.
<?php
$json_object = file_get_contents('fb.json');
if(!$json_object) {
echo "oops, cant read the file";
}
// remap json_object
$json_object = json_decode($json_object,true);
foreach($json_object['data'] as $item) {
$items[] = "I like" . ' ' . $item['id'];
/* If you want to just echo " I like xyz" etc
* use echo "I like" . $item['id'];
*/
}
$list = implode(',',$items);
echo $list;
?>

Categories