How to generate json response using php - php

How to generate json response using php
In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails;
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
print_r($jsonResponse);
When printing the data i'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
But i want output like this, Because i have to generate a jstree using json
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]

I would recommend that you use the output from json_encode as it is. Takes less bandwidth. Only reason I see for all the whitespace is for debugging, and for that I'd rather use FireBug and/or JSONView in FireFox.
Anyways, if you really want to, you can maybe try the JSON_PRETTY_PRINT flag? Seems this was added in 5.4.0 though, so maybe not the version you're on supports it... There seems to be options you can use for that in the comments there though. Maybe you can find something useful? http://www.php.net/manual/en/function.json-encode.php#102091
You say you have to create a jstree now, and that doesn't really have anything to do with what you're asking. You're two examples of data doesn't look anything alike at all. json_encode does not do anything special or magic. It just takes data and turns it into JSON. It's your job to make that data look correctly first, before encoding it. Your DB query most likely returns a set of flat rows, and you'll have to loop through it and somehow generate your tree the way you want it. You can probably find other questions here about how to create tree structures out of flat DB results.

Since you are using Zend Framework, I recommend you to use Zend_Json. Zend_Json is a pretty useful component to use in order to format Json from any supported format (object, array, xml...).
Zend_Json::decode() and Zend_Json::encode() will allow you to encode and decode Json and prettyPrint() is used to make your output prettier.
Edit:
As Svish said, your two examples doesn't look alike, so it's kind of hard to guess what you want to put inside your tree.
What you need is to create your own array, so you can make it look like the way you want.
For example, let's say you only want one row from your database in your tree, then your array would be something like this:
$v = array(
array(
"data" => array("icon" => "ICON",
"title" => $row->name),
"attr" => array("rel" => "REL",
"title" => "TITLE",
"id" => $row->group_id),
"state" => "closed"));
echo Zend_Json::encode($v);
These lines should echo something like in your examples.
To make it works with your fetchAll(), a simple foreach will do it.

Related

PHP Parse Text into Array

I have an HTML file that I have downloaded using curl and inserted into a string. The HTML file has a lot of content but I am looking to parse a certain section of the document and insert this section into an array. The tricky part of this is that the section that I'm trying to parse is NOT HTML, it's code in JavaScript block:
<!-- script block -->
<script type="text/javascript" src="//external.site.com/76b07.js"></script>
<script>....code.....
"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"},
"235534":{"itemId":"235534","type":"1","image":{"url":"thisotherpic.jpg"}:"summary":"This Other Item"},
</script>
How can I import item information as an array?:
$array = array( "itemId" => "235533", "type" => "0", "image" => "thispic.jpg", "summary" =>"This Item" );
You might use a RegExp to match "....":{....} located between <script> tags. The strings, you're interested in, are JSON variables.
Once you have each json variable in a string, you could try with json_decode()
$json_string = '"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"}';
$json = json_decode($json_string);
$myArray = (array)$json;
Try json_decode function in php
You would first need to figure out how to isolate the data structure using whatever string searching methodologies you can use that are repeatable even when the data changes. It is hard to say what this might be without further context from you about the content around the data structure - i.e. what is the same in all cases, and what varies.
You would then eventually get the data strings and json_decode them as others have suggested.
use regex to match them
preg_match_all('/[0-9]+":{"itemId":"(?P<itemId>[0-9]*)","type":"(?P<type>[0-9]{1})","image":{"url":"(?P<image>.*)"}:"summary":"(?P<summary>.*)}/',$mystring,$elements,PREG_SET_ORDER);
then loop through $elements to get your values
Use explode. For example, something like
$array = explode('","', $string);
that would get close to what you want.
Edit:
This looks like a better fit for you.

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

json_decode fails

I'm fairly new to json, and I'm having an issue with json_decode. I think I know why, but I haven't been able to sort out how to fix it.
Basically, I have a URL that supplies json info. I grab it using cURL, and return it as a PHP variable, and that's working just fine. I can print_r out all the info I want. However, when I use json_decode($json, true), it returns NULL.
I THINK it's because, technically, what's being returned is not a string, but more like an object - and I can't sort out how to grab the contents of that object.
For example, when I return the json stuff as a php variable:
print_r($json);
The output returned looks like so (I won't do it exactly, because it's HUGE, so I'll show you the layout to keep it simple)
MyThing.returnedItems({MyThing.returnedItems({
"projects":[{
"completed":"2010-12-21",
"status":"finished",
"favorited":0,
"started":"2010-12-20",
"percentage":78,
"permalink":"slug to post",
"size":"One size",
"thumbnail":{"src":"full path to full size image",
"medium":"full path to thumbnail"},
"name":"Some title here",
"notes":"description here",
"url":"URL to page",
"comments":0},
So you can see it's like a nested array. I don't mind that, but I'd like to be able to access all the key/value pairs of these arrays as PHP variables. But it seems because of the "MyThing.returnedItems()" surrounding it, it doesn't see it as a string to decode, so I get a NULL value every time.
Anyone know what I'm missing here? Once I figure out how to grab the stuff inside there, I think I've got it (simple foreach or whatnot to get the rest of the variables as needed), but I just can't seem to get in there.
This is valid JSON
{
"item1": [
{
"something": [],
"something else": "some value"
}
],
"another fun thing": [
{
"more fun": "fun value 1",
"even more!": "fun value 2"
}
],
"item2": {
"another thing": "another value"
}
}
This is not!
MyThing.returnedItems({
"item1":[{"something:[],
"something else": "some value"},
"another fun thing": [{"more fun": "fun value 1",
"even more!": "fun value 2"}]
],
"item2":{"another thing": "another value"}
})
Its a javascript method call
Okay, I just wanted to add that you all REALLY helped me out. Especially MaX, because by knowing the "official term" of what was happening, I had better searches and ended up finding some really interesting code that eventually landed me my solution. However, I did discover the reason why I was having my json wrapped in that weird function method call: the URL that the site gave me to access their API actually had that call in it, so it was returned wrapped in it. In other words, the json file URL I had was like so:
somesite.com/apicall.json?key=1234567890&callback=MyThing&version=0...
so as soon as I removed that "callback" section - BAM the json was no longer wrapped, and a whole new world of foreach functions opened up to me. So, even though the solution ended up being a REALLY stupid oversight on my part, I wanted to thank you all for your input, because I learned a whole lot of stuff I wasn't planning to today XD
Oh, and the code that actually ended up working (after I got rid of the callback part of the URL, because json_decode was still returning NULL on me) was this:
$data = json_decode(file_get_contents($json), true);
print_r($data); // array of everything available for me to mess with!
Thanks again for your help, everyone :) I REALLY appreciate it!

Pass a list from php or xmlhttp.responseText to javascript

I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list.
I have a static list working in this form:
var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];
I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.
Does anyone have any suggestions or solutions? Your help would be greatly appreciated.
Kallum
Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.
Then in your code, after you receive the output from the PHP script, run this:
var mark_list = JSON.parse(responseText);
Based on the output from the PHP script, you may need to do this:
var stuff = JSON.parse(responseText);
var mark_list = [stuff];
This will convert the JSON string the PHP returns into an actual javascript object.
In your PHP code you can do something like this:
$output = array(
array(
'EntId' => 3,
'x' => 100,
'y' => 400,
),
);
echo json_encode($output);
Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.
responseText will indeed just be a text represented by a string, so the way you are outputting it right now won't just do the trick all on its own. There are basically two ways you can do this:
In your javascript, you parse the output the server is giving you. This can be done onn a pure string in whatever way you feel like doing it. For example, you could write javascript to parse the format you gave with curly braces and a colon based syntax. Alternatively, you could use another format (like XML) which will reduce the work a little, but will still leave the interpreting of the output for you to do in the javascript.
You can output to a format used to describe objects and lists. JSON would be the big example of such a format. If you output in JSON, you will get something that resembles the format you used above (JSON stands for Javascript Object Notation and is based on parts of the syntax of javascript) and all you will have to do to be able to use it is to get to the data you want to get to. You can use JSON.parse() for this on most browsers, but an alternative with more widespread support is jQuery's jQuery.parseJSON() (for which you would use jQuery, which you should also provide in that case)

mongodb php $push not inserting array

I've seen a bunch of the other Mongo PHP $push questions up here on SO, but for some reason none of what they're saying is working, so I'm posting my own version.
Basically, I'm trying to follow a guideline set by 10gen where representing something like a news feed or blog/comment post should be done using buckets - making documents that hold a certain number (50) of events (comments, etc.), and then creating multiple documents as the content grows.
What I'm trying to do is push documents ($event) into an array (events), but there seems to be some confusion with PHP when the document doesn't exist (upserting). I tried to do it with an insert, but insert and $push don't play well together.
Here's what I have right now:
$historyDoc = array('_id'=>$uID, 'count'=>1,
array('$push' => array('events' => $event)));
$query = array('_id'=>$uID);
//add user to history
$collection->update($query,$historyDoc,
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
Where $event is a properly-formatted array (document) of things (e.g. timestamp, userID, action, name) and $uID is a MongoID object taken from another collection.
The result that I get is this:
{
"_id": {
"$oid": "4f77ec39fef97a3965000000"
},
"0": {
"$push": {
"events": {
"timestamp": 1333259321,
"action": "achievement",
"pts": 0,
"name": "join"
}
}
},
"count": 1
}
Which is good, because my document is at least showing up right, but how the hell is there a key with a "$" in it? It's not like I'm failing to escape the $...I've been very intently using single quotes for that exact reason.
Maybe there's something I'm missing, or maybe I broke PHP, but I've been wrestling with this one for awhile and there's nothing I can thing of. It's holding my whole project up, so....>:/
Your update document is ill-formed, try this:
$historyDoc = array('_id' => $uID,
'count' => 1,
'$push' => array('events' => $event));
It's not the most elegant solution, but it looks like it works. Apparently there's a problem with using $push on a new document (insert or upsert) (EDIT: It might actually be the issue with combining atomic and non-atomic thing that's the problem. You can't use atomic operators on _id, so...). However, you can get around it by inserting the document first and then updating/upserting it.
In order to initialize an array in Mongo via PHP, you need to create a document with an empty array a a value, as seen here:
$historyDoc = array('_id'=>$uID.'-0',
'count'=>1,
'events'=>array());
From there, you can simply take what you were going to put into the first index and upsert it later:
$collection->update($query, $historyDoc,
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
$collection->update($query,
array('$push'=>array('events'=>$event)),
array('safe'=>true,'timeout'=>5000,'upsert'=>true));
This yields a resulting document of the form:
{
"_id": "4f77f307fef97aed12000000-0",
"count": 1,
"events": [
{
"timestamp": 1333261063,
"action": "achievement",
"pts": 0,
"name": "join"
}
]
}
Source: Mongo PHP Manual - Updates

Categories