How to format js object to php array? - php

So I found some answers on how to do this, but none of them actually worked, i.e. json_decode(). This is what I did:
I created js object/array
Then I passed it to php file via Ext.Ajax.Request as JSON.stringify(js object)
Now in my php I see the result of that string as follows: ["James;","George;"]
I want to get it as an php array like (James, George). Any easy way to do this or I have to remove unnecessary parts manually?

OK, I was looking at this problem for a while and finally got the answer.
Inside php, I needed to add json_decode(stripslashes($scenarios)), where $scenarios = ["James;","George;"].
Code: ($scenarios is sent from js file via Ajax using JSON.stringify(js object))
<?php
$scenarios = empty($_GET['scenarios']) ? false : $_GET['scenarios'];
// more code for validation
$arr = json_decode(stripslashes($scenarios));
?>
Now $arr will become regular php array.

Use html_entity_decode function

Related

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.

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

zend php multiple array json_encoding

I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>

Simple JSON request in PHP

I have the following json
country_code({"latitude":"45.9390","longitude":"24.9811","zoom":6,"address":{"city":"-","country":"Romania","country_code":"RO","region":"-"}})
and i want just the country_code, how do i parse it?
I have this code
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = file_get_contents($json);
var_dump(json_decode($jsonfile));
?>
and it returns NULL, why?
Thanks.
<?php
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>
You just need json not jsonp.
You can also try using json_decode($json, true) if you want to return the array.
you're requesting jsonp with http://api.wipmania.com/jsonp?callback=jsonpCallback, which returns a function containing JSON like:
jsonpCallback({"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}})
and not JSON itself. change your URL to http://api.wipmania.com/json to return pure JSON like:
{"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}}
notice the second chunk of code doesn't wrap the json in the jsonpCallback() function.
The website doesn't return pure JSON, but wrapped JSON. This is meant to be included as a script and will call a callback function. If you want to use it, you first need to remove the function call (the part until the first paranthesis and the paranthesis at the end).
If your server implements JSONP, it will assume the callback parameter to be a JSONP signal and the result will be similar to a JavaScript function, like
jsonpCallback("{yada: 'yada yada'}")
And then, json_decode won't be able to parse jsonpCallback("{yada: 'yada yada'}") as a valid JSON string
If country_code( along with closing parenthesis are include in your json, remove them.
This is not a valid json syntax: json
You are being returned JSONP, not JSON. JSONP is for cross-domain-requests in JavaScript. You don't need to use it when using PHP because you aren't affected by cross-domain-policies.
Since you are getting a string from the file_get_contents() function you can do a replacement of the country_code( text (this is the JSONP specific part of the response):
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
?>
Note
This works but JKirchartz's solution looks better, just request the correct data rather than messing around with the incorrect data.
Obviously in this situation, using the correct URL to access the API will return pure jSON.
"http://api.wipmania.com/json"
A lot of people are providing an alternative to the API in use, rather than answering the OP's question, so here is a solution for those looking for a way of handling jSONp in PHP.
First, the API allows you to specify a callback method, so you can either use Jasper's method of getting the jSON sub string, or you can give a callback method of json_decode, and modify the result to use with a call to eval. This is my alternative to Jasper's code example since I don't like to be a copy cat:
$json = "http://api.wipmania.com/jsonp?callback=json_decode";
$jsonfile eval(str_replace("(", "('", str_replace(")", "')", file_get_contents($json)))));
var_dump($jsonfile);
Admittedly this seems a little longer, more insecure, and not as clear to read as Jasper's code:
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
Then the jSON "address":{"city":"-","country":"Romania","country_code":"RO","region":"-"} tells us to access the country_code like so:
$jsonfile->{'address'}->{'country_code'};

JSON from Javascript not decoding in PHP

I've been going bananas trying to get some data from Javascript on one page to post to a php file asynchronously. I'm not even attempting to do anything with the data, just a var_dump to spit back out from the ajax call. NULL over and over again.
I've checked the JSON with JSONLint and it validates just fine. I'm getting my JSON from JSON.stringify - Firebug tells me I'm getting the following:
{"items":[["sa1074","1060"],["sa1075","1061"]]}
I've tried php://input, as well as json_decode_nice from the PHP manual comments about the function, and I've tried using utf8_encode - is there something wrong with my JSON?
EDIT: Derpity dee probably should have planned this post a bit more haha. Here's my PHP (using a suggestion from PHP manual comments)
function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
if (isset($_POST['build'])){
$kit = file_get_contents('php://input');
var_dump(json_decode_nice($kit));
}
And the JS used to create it:
var jsonKit = JSON.stringify(kit);
$.post("kits.php?", {"build" : jsonKit},
function(data) {
$("#kitItems").html(data);
});
Also: Our host is on PHP 5.2 - I found this out when I uploaded a perfectly good redbean class only to have it explode. Had to re-implement with legacy redbean. Our host is busted.
SOLVED: Thanks to all who commented. Didn't think to check $_POST to see what was coming in. Quotes were being escaped with slashes in the $_POST and json_decode was choking on it. Adding this line before decoding solved the problem. Also forgot to set true to return an associative array. Thanks!
$kit = str_replace('\\', '', $kit);
Without seeing code - I'm just guessing here ... are you using a true assoc variable in your json_decode()?
<?php json_decode($jsonString, true); ?>
That had me stumped on a decode for quite some time my first time trying to decode something,

Categories