creating json object from sql database using php - 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);

Related

Convert newline in JSON and print in textarea using PHP

I already did my research first, but some topics didn't solve my issue and some quite different from what issue I have. I have a JSON that didn't print out the entire data and as upon checking the culprit is the newline when it was a value (it is my first time knowing it, my bad).
<?php
$jsn = <<<_JSON
{
"name": "Editorial",
"links": "default",
"data": [
{
"Status": "Pending",
"Tags": "Documentation",
"Info": "all documentation to be ready by Friday"
},
{
"Status": "Published",
"Tags": "Pros and Cons Limits",
"Info": "documentations about-Realtime\n-Speed per sec\n-API Limit"
}
]
}
_JSON;
$data = json_decode($jsn, true);
$output= $data['links'];
echo $output;
It will not print any output as the \n was there. So I was planning to do in the future, if they tried to use a newline, I will just temporary change the \n to other characters and decode it back. And that's where I'm having a hard time.
As testing it wasn't working for me.. Converting it back and show in textarea.
$txt = "Documentations about%2Realtime%2Speed per sec%2API Limit";
$value = str_replace("%2", '\n', $txt);
$textArea = '<textarea rows="4">'.nl2br($value).'</textarea>';
echo $textarea;
//output
//documentations about\nRealtime\nSpeed per sec\nAPI Limit
If anyone can help me in your spare time, I really appreciate it.. Thanks in advance.

Valid JSON from text file

I understand there are other similar posts about this, I am going out of my wits end here.
I have a few files with some JSON (all valid according to online validators, eg. jsonlint) - see EDIT below.
$contents = file_get_contents(DATA_PATH.'/'.$type.'.json');
$data = json_decode($contents, true);
echo var_dump($data);
Returns NULL
If I echo $contents, I do get output.
I'm not sure what is wrong? I understand file_get_contents gets it into a string, however, how do I get it in a valid JSON? Would using fopen() be any different?
I even added the JSON to a variable but had the same outcome... I must be stupid.
Note: Most JSON I'll get will be from an API, these file-based JSONs are for testing purposes.
Thanks.
EDIT: Sample json
{
"data": [{
"id": 1,
"name": "Albania",
"alpha2code": "AL",
"alpha3code": "ALB",
"capital": "Tirana",
"flag": "https://cdn.elenasport.io/flags/svg/1",
"region": "Europe",
"subregion": "Southern Europe",
"timezones": [
"UTC+01:00"
]
},
{
"id": 3,
"name": "Algeria",
"alpha2code": "DZ",
"alpha3code": "DZA",
"capital": "Algiers",
"flag": "https://cdn.elenasport.io/flags/svg/3",
"region": "Africa",
"subregion": "Northern Africa",
"timezones": [
"UTC+01:00"
]
}]
}
Your file might have a UTF-8 BOM which is not copied when you copy-and-paste your sample JSON to a (web based) validator. It's an invisible mark at the beginning of your file.
If you run echo bin2hex(file_get_contents(DATA_PATH.'/'.$type.'.json')) your file should begin with 7b, which is a {.
If it starts with efbbbf and then a 7b, there is a BOM. Either strip it out yourself or re-save your JSON without one using a text editor like Sublime Text which allows you to configure that.

json - how to get data from json where user's input will come on %s [duplicate]

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

order of JSON with multiple arrays in php with varying number of objects

I have never needed json previously, so I have almost zero experience...
I am outputting multiple arrays into a json file using the following code:
$file= 'myfile.json';
$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
file_put_contents($file, $newcont);
This is working as expected, and the output gives me something similar to this:
"name": [
"joe blogs",
"random name 2",
"random name 3",
etc,
etc
],
"busname": [
"ABC business",
"DEF business",
"HIJ business",
etc,
etc
],
"busdesc": [
"We do stuff",
"We do other stuff",
"We don't do anything",
etc,
etc
],
etc
Is it possible to (with a simple method) have the output to be more like:
"id1": [ "joe blogs", "ABC business", "We do stuff", etc ]
"id2": [ "random name 2", "DEF business", "We do other stuff", etc ]
"id3": [ "random name 3", "HIJ business", "We don't do anything", etc ]
etc
Layout is not particularly important, but getting them grouped together is.
I have had little success with getting relevant results from Google searches.
The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.
Many thanks
Edit:
I have undeleted this as my attempt at fixing did not work.
Here is the code:
$results = mysqli_query($con,"SELECT * FROM membersites WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
$r1 = $business['id'];
$id[]=$r1;
$r2 = $business['name'];
$name[]=$r2;
$r4 = $business['busname'];
$busname[]=$r4;
$r5 = $business['busdesc'];
$busdesc[]=$r5;
$all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}
$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.
Again, please bare in mind that this is the first project that I have had to output any json files.
Any help will be appreciated :)
Edit 2 (for clarity)
Final output needs to look like this
{
[
{
"id":"1",
"name":"joe blogs",
"busname":"ABC business",
"busdesc":"We do stuff"
},
{
"id":"2",
"name":"joe blogs",
"busname":"random name 2",
"busdesc":"We do other stuff"
},
etc
]
}
This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.
Apologies for being awkward.
When you loop on your records from DB, build a multi-dimensional array:
while($business = mysqli_fetch_array($results))
{
$all[] = [
'id' => $business['id'],
'name' => $business['name'],
'busname' => $business['busname'],
'busdesc' => $business['busdesc'],
];
// or
$all[] = $business;
// or
$all[ $business['id'] ] = $business;
}
Then you can encode your multidimensional array into JSON like this:
$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])
I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:
$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);
You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.

Adding JSON to PHP file

I am trying to add a JSON script to a php file in my sites admin. My goal is to have the JSON run when the order status is change to 3 (shipped).
I am pretty sure I am going about this all wrong but I am not sure what to do yet. here is my code:
if ( ($check_status['orders_status'] != $status) && $check_status['orders_status'] == 3) { ?>
<script>
POST https://api.yotpo.com/oauth/token
{
"client_id": "### Your client_id ###",
"client_secret": "### Your client_secret ###",
"grant_type": "client_credentials"
}
POST https://api.yotpo.com/myapi/purchases
{
"validate_data": true,
"platform": "general",
"utoken": "### YOUR UTOKEN ###",
"email": "client#abc.com",
"customer_name": "bob",
"order_id": "order_1",
"order_date": "2010-10-14",
"currency_iso": "USD",
"products": {
"SKUaaa12": {
"url": "http://example_product_url1.com",
"name": "product1",
"image": "http://images2.fanpop.com/image/photos/13300000/A1.jpg",
"description": "this is the description of a product",
"price": "100",
"specs": {
"upc": "USB",
"isbn": "thingy"
},
"product_tags": "books"
}
}
}
</script>
<?php } ?>
First of all, there is nothing in my code that says hey, this is JSON besides the tag.
do I need to have the json in a sepearate json file? Or do I need to convert this script to php?
First of all, Nikita is correct that JSON does not run - it is not script. It is a standardized way to store information.
PHP has native JSON handling functions and can easily take existing objects or arrays and convert them to JSON.
<?php
$json = json_encode($my_data);
?>
<input type="hidden" name="post_data" <?php echo 'value="'.$json.'" ?> />
Then when you send this variable $json to the next page, you'll unpack it like so
$my_data = json_decode($_POST['post_data']);
This is a pure PHP implementation, though JavaScript does nice functions to stringify to/from json as well.

Categories