How can I display JSON data using PHP - php

I have already created a dynamic JSON file.
My code is:
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro)) {
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
How can I get data from the JSON file? Using a while loop or anything similar?

$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($res))
{
$records []= $rowpro;
$json_string=file_put_contents("product_file.json",json_encode($records));
}
First, you have mistake on line 2
mysql_fetch_array($res)
AND NOT
mysql_fetch_array($respro)
Second, Use file_get_contents and json_decode functions
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];
Thanks

This is how you see the posted json data in your php file.
I would prefer that:
$json_string=json_encode($records);
you must put the header
header('Content-Type: application/json;charset=utf-8');
and other side
$file=file_get_contents('php://input');
$obj = json_decode($file, true);
$param = $obj['param'];

First of all the way you are writing to the file inside the while loop is wrong.. Because you are unneccesarily calling the file_put_contents() again and again which is simply degrading your code performance..
So rewrite your code to this..
$res = mysql_query("select * from tbl_product where category='saree'");
while($rowpro=mysql_fetch_array($respro))
{
$records[]= $rowpro;
}
file_put_contents("product_file.json",json_encode($records));
To read the JSON data , make use of file_get_contents()
Like this..
$jsonData = file_get_contents("product_file.json");
echo $jsonData; //<--- Prints your JSON

In PHP ,
header('Content-Type: application/json;charset=utf-8');
$str = file_get_contents('product_file.json');
$jsonData = json_decode($str, true); //json decode
And in jquery you can use jQuery.getJSON example ,
$.getJSON( "product_file.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Related

Append php loop data to JSON object

I need looped php data in an html template so I know it has something to do with JSON however not a JSON expert and cannot find much help in searching the web.
$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr = json_decode($data, TRUE);
$dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
//$json = json_encode($dataArr);
}
}
}
$json = json_encode($dataArr);
print_r($dataArr);
But it only appends one row. In fact it deleteds that data that's already in my dataArr and just adds one row from my loop? Maybe I'm approaching this situation completely wrong?
You set your $dataArr inside the while-loop. So each time the loop is runs, it will be overwritten. Also, it makes more sense and it's much more clear when you handle it as an array (or object) and afterwards convert it to JSON.
$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));
foreach($uniqueFranchise_id as $franchise)
{
$sqlFranchise = "select * from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
while($rowFranchise = $resultFranchise->fetch_assoc())
{
$dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
}
}
}
$json = json_encode($dataArr);
echo $json;
You shouldn't be building the string up by yourself, you should build the data and then JSON encode the result (comments in code)...
$dataArr = '[
{
"name": "Dylan",
"page_link": "https://mypage.com/"
}
]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
// Read just the data you need from the table
$sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
$resultFranchise = $conn->query($sqlFranchise);
if($resultFranchise->num_rows > 0)
{
// Read all of the rows into an array
$newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
// Add in existing data
$dataArr = array_merge($dataArr, $newData);
}
}
// Now encode the list of elements into 1 string
echo json_encode($dataArr);
You should also look into prepared statements if this data is not trusted to stop SQL injection.

JSON parse URL with PHP JSON decode

I have JSON data:
{"took":3,
"timed_out":false,
"_shards":{ "total":5,
"successful":5,
"failed":0
},
"hits":{"total":105,
"max_score":1.0,
"hits":[
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW0",
"_score":1.0,
"_source":{"message":"james,wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"fa1368a93aa39b2346329c1734be1f4b",
"lname":"wonder"
}
},
{"_index":"csv",
"_type":"logs",
"_id":"AVeyr-BQodQ9UhW1sdW1",
"_score":1.0,
"_source":{"message":"muskaan, wonder\r",
"#version":"1",
"#timestamp":"2016-10-11T07:40:52.332Z",
"path":"D:\\logstash-2.4.0\\bin\\Book1.csv",
"host":"CHNL-LT-544",
"fname":"479085e94d305129527fa80978613e95",
"lname":"wonder"}
},
{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW3","_score":1.0,"_source":{"message":"altimetrik,india\r","#version":"1","#timestamp":"2016-10-11T07:40:52.333Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"8b3ecf275832c79b36d62d74f47257c9","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdW8","_score":1.0,"_source":{"message":"kool,indiae\r","#version":"1","#timestamp":"2016-10-11T07:40:52.335Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"indiae"}},{"_index":"csv","_type":"logs","_id":"AVeyr-BQodQ9UhW1sdXA","_score":1.0,"_source":{"message":"ds,dssd\r","#version":"1","#timestamp":"2016-10-11T07:40:52.336Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"91594a75bc6bfb0ec800d4f454e1fe87","lname":"dssd"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXf","_score":1.0,"_source":{"message":"kool,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.839Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"d2edbdce885720c70f38f36748c37600","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytJ0iodQ9UhW1sdXi","_score":1.0,"_source":{"message":"karnataka,india\r","#version":"1","#timestamp":"2016-10-11T07:46:02.840Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"2a0785caed6bfd2ffb6ad5a449f2bd0e","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdXq","_score":1.0,"_source":{"message":"james,wonder\r","#version":"1","#timestamp":"2016-10-11T07:48:39.550Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"fa1368a93aa39b2346329c1734be1f4b","lname":"wonder"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX0","_score":1.0,"_source":{"message":"rajasthan,india\r","#version":"1","#timestamp":"2016-10-11T07:48:39.558Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"449b07d9038569b2d69243dadfae0371","lname":"india"}},{"_index":"csv","_type":"logs","_id":"AVeytv9hodQ9UhW1sdX5","_score":1.0,"_source":{"message":"najeeb,shariff\r","#version":"1","#timestamp":"2016-10-11T07:48:39.573Z","path":"D:\\logstash-2.4.0\\bin\\Book1.csv","host":"CHNL-LT-544","fname":"be7a5e98258338fa63086f44e8bd1850","lname":"shariff"}}]}}
I want to print only 2 fields from this JSON; fname and lname. Please tell me how I can achieve this using PHP.
$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits'] as $item) {
print $item['fname'];
}
But getting error Undefined index
$url = 'localhost:9200/csv/_search';;
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['hits']['hits'] as $item) {
echo "<p>{$item['_source']['fname']}</p>";
echo "<p>{$item['_source']['lname']}</p>";
}
Array path of fname and lname goes like [hits][hits][0][_source][fname] and [hits][hits][0][_source][lname]. [hits][hits] should be iterated in the loop to access each _source element.
As RiggsFolly said, you need to do print_r($json) to see how the array is structured especially when you encounter nested arrays.
Hope it helps!

php json_decode and Jquery Nestable

I'm using jquery Nestable (http://dbushell.github.io/Nestable/).
I'm trying to intercept data from it when I change order on mine nestable elements..
$('.dd').nestable().on('change', function() {
var json_text = $('.dd').nestable('serialize');
$.post("/includes/processes/core.php", {
cmd: 'nestable',
table: table,
data: json_text
}, function(response){
alert(response);
});
});
In core.php I've done:
$data = $_POST['data'];
$data = json_decode($data, true);
function parseJsonArray($jsonArray, $parentID = 0) {
$return = array();
foreach ($jsonArray as $subArray) {
$returnSubSubArray = array();
if (isset($subArray['children'])) {
$returnSubSubArray = parseJsonArray($subArray['children'], $subArray['id']);
}
$return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
$return = array_merge($return, $returnSubSubArray);
}
return $return;
}
$readbleArray = parseJsonArray($data);
Than I've to manipulate this array but I can't go on because response is:
"json_decode() expects parameter 1 to be string, array given in core.php on line (where is "$data = json_decode($data, true;")"
If I change json_decode($data, true) with json_encode($data) this is the response:
"Invalid argument supplied for foreach() in core.php on line (where is "foreach ($jsonArray as $subArray);")"
Please Help me..
Try removing this line because $.post doesn't do json encoding.
$data = json_decode($data, true);
Use JSON.stringify. It will turn your javascript object into a JSON string, which will allow you to post it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You can than decode it in PHP. To do this, in your jQuery code replace this:
data: json_text
With:
data: {json_text: JSON.stringify(json_text)}

parse json in javascript

I load a php/json file. This is my json file:
echo '{';
echo '"position":[';
while($inhoud = mysql_fetch_array($result))
{
echo '{';
echo '"lat":"'.$inhoud['lat'].'",';
echo '"long":"'.$inhoud['long'].'",';
echo '}';
}
echo ']}';
This works. I want to load it in my javascript and do it like this:
$.getJSON('req/position.php', function(data) {
$.each(data, function(key, val) {
newLatLng = key;
});
});
but this doesn't work. It loads the file but i don't get this data. What should i do?
Thanks,
I think you have some syntax errors in the JSON output.
When you output "long" data, you append a comma , at the end, but you should not, because "long" is the last key of the object.
You print out an object in a while cycle. These objects are part of an array. So, except for the last one, you have to append a comma , after the closing }.
And, if I can ask, why you are not using the json_encode() PHP function, instead of build all the JSON string manually? With it, you build all the data as normal PHP array, and then encode (translate) it in JSON. You will avoid all these annoying syntax stuffs.
Just try it:
$data = array();
$data['position'] = array();
while($inhoud = mysql_fetch_array($result))
{
$data['position'][] = array(
"lat" => $inhoud['lat'],
"long" => $inhoud['long']
);
}
echo json_encode($data);
You have your co-ordinates defined in the array named position. You need to iterate through that. The Array contains objects with the properties lat and long. If you want to use the values, you should try something like:
$.getJSON('req/position.php'), function(data){
$.each(data.position, function(index, value){
var newLatLng = { latitude: value.lat, longitude: value.long };
});
});
Return proper header in PHP script
header('Content-type: application/json');
And it should work.
Also use json_encode to encode PHP values into valid JSON.
Constructing JSON in php through strings works but is primitive. Start constructing an array and use json_encode().
$arr = array();
while($inhoud = mysql_fetch_array($result)){
$temp = array();
$temp['lat'] = $inhoud['lat'];
$temp['long'] = $inhoud['long'];
$arr[] = $temp;
}
echo json_encode($arr);
If all that you select in your mysql query is 'lat' and 'long' you could also just place $inhoud into $arr inside your while loop like so.
while($inhoud = mysql_fetch_array($result)){
$arr[] = $inhoud;
}
If you do this just make sure you only select columns in your mysql query that you would want to output in JSON.
$.getJSON('req/position.php', function(data) {
var obj = JSON.parse(data);
// At this point, obj is an object with your JSON data.
});
Source: MDN

php array to 2d Javascript array

I'm working on passing 2 fields of SQL through php to javascript. I have read many tutorials on how to create a multidimensional javascript array. Where I get confused is how to code from php to javascript. I have seen a couple of tutorials on how to get the php data to javascript, but none on how to do this with 2 dimensions.
My first hangup is that if I'm creating a multidimensional array I need to count the number of records in my sql data before I declare the java array right?
update:
I got the data to JSON format as suggested below. Is there a way for me to get all of the contents printed to the web page so that I can see them and then narrow down what is displayed?
update III:
code:
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$new_row = array();
$new_column = array();
while($info = mysql_fetch_array($data)){
foreach( $info as $row_num => $row)
{
$thisItem = $row;
$new_row[] = $thisItem;
}
array_push($new_column = $new_row);
}
$json = json_encode($new_column);
echo $json;
?>
Working code:
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row['userID'],$row['date'],$row['lat'], $row['longi'], $row['alt']);
$json = json_encode($aData);
echo $json;
Fill a PHP array first, it's easier than building the string for a javascript array. Then - as ThiefMaster said as comment - use JSON to make the javascript array.
In PHP, you can use JSON PECL extension
<?php
$arr = array( 1=>array(3,4),
2=>array(4,5));
$json = json_encode($arr);
echo $json;
?>
Output
{"1":[3,4],"2":[4,5]}
In Javascript
var obj = JSON.parse('{"1":[3,4],"2":[4,5]}');
for(var i in obj){
for(var j in obj[i]) {
console.log(obj[i][j]);
}
}
JSON.Parse is for Gecko (Firefox alike), for cross-browser javascript JSON parse check jQuery.parseJSON or https://stackoverflow.com/search?q=json+parse+javascript
Sample implementation in PHP/jQuery, would be something like this:
json.php
$arr = array( 1=>array('Name', 'Age'),
2=>array('Fares','18'));
$json = json_encode($arr);
echo $json;
json.html
<html><head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$.getJSON('json.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
</script>
</body>
</html>

Categories