I've got following array titled $val in PHP :
Array
(
[page_id] => 208
[invite_emails] =>
[invite] => Array
(
[0] => 970
[1] => 991
[2] => 992
)
)
I only want to convert the above array into a valid JSON request and send it to some web service URL.
How should I do it? Please help me.
Thanks in advance.
Your question is rather broad, but to convert a php array into a JSON object is very easy.
$jsonString = json_encode($array);
As for sending it to the URL, this question contains some good info.
Or if you want to use curl, this resource is pretty good.
As others have posted, use the following to json encode your array:
json_encode($val);
Now, your problem is sending this to your web service via parameter. The way I generally send complex parameters via GET parameters is by base64 encoding.
$param = base64_encode(json_encode($val));
Now you can send $param just like any other parameter. Take a look at Guzzle for making HTTP requests from PHP.
I am stuck on this. This is a json_encoded string by the Wordpress plugin and saved into database.
I want to read it from my own database query. I am getting null when tried with var_dump .
It has some properties of code which is creating problem, I think.
Below is the data where from i want to read usable data for my use. I am using PHP and Mysql.
a:3:{i:0;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:3:"100";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:0;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}i:1;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:3:"200";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:0;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}i:2;O:27:"WpProQuiz_Model_AnswerTypes":7:{s:10:"*_answer";s:8:"Infinite";s:8:"*_html";b:0;s:10:"*_points";i:1;s:11:"*_correct";b:1;s:14:"*_sortString";s:0:"";s:18:"*_sortStringHtml";b:0;s:10:"*_mapper";N;}}
I know this looks nasty but copy and try to decode it.
Ohh In Wordpress you can do as follows
$serialized = 'a:3:{i:0;s:5:"examp";i:1;s:6:"exampl";i:2;s:6:"examp2";}';
var_dump(unserialize($serialized));
Array
(
[0] => examp
[1] => exampl
[2] => examp2
)
While working with the cakephp, I found an issue mentioned below.
Fetched the encrypted field info from DB (encrypted using Security::rijndael)
Passed this whole data as an array format to the custom Library(Own created lib).
When i echoed the data in lib as well in controller I amazed to see the result. The value (encrypted one) are showing blank in the lib. Is I missed anything in codding? I searched on google but didn't get the satisfactory answer, Please help me out. Your help will really be appreciated.
Here is result i am getting in controller and Library respectively
Array
(
[0] => Array
(
[value] => s�i�(�RTf���cBЉF� | �r�n#ô�
)
)
Array
(
[0] => Array
(
[value] =>
)
)
Check your character encoding; a place I worked at ran into a similar issue and it was due to our db trying to encode characters it did not support. UTF-8 generic is a, well, generic encoding type.
I've been using json_encode for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
I have the following code:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
This gives me the following results:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Can anyone tell me why json_encode adds slashes?
update
#Quentin said that something is happening between json_encode and .parseJSON and he's right.
Doing a alert(data.toSource()); gives me the dollowing result:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.
Could it be that the Plupload bind does something to my returned data?
This is my js script:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/" and "\/" are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.
This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\".".
This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]
Make sure your php script has the right header or it will add the slashes
header('Content-Type: application/json');
I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.
json_encode will always add slashes.
Check some examples on the manual HERE
This is because if there are some characters which needs to escaped then they will create problem.
To use the json please Parse your json to ensure that the slashes are removed
Well whether or not you remove slashesthe json will be parsed without any problem by eval.
<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>
This is my code and i m able to parse the JSON.
Check your code May be you are missing something while parsing the JSON
stdClass Object ( [free] => 100% δωρεάν [meetsingles] => Γνωρίστε Singles [searchprofiles] => Προφίλ Αναζήτηση )
I have a JSON array that after decoded 'json_decode' and printed to screen it looks like above - using UTF8 for Greek.
This is how I print it:
$siteLanguages = json_decode($result);
print_r($siteLanguages);
When I try to access one of the values the page displays only until the point of the print and then it stops loading - eg: like half a page will show - comment this out and the whole page shows - below is how I'm trying:
print $siteLanguages['searchprofiles'];
I can't see why I can't use the associate array like any other.
Is there a trick I'm missing here?
Should the decoded json array show 'stdClass Object' when printed?
thx
I think you're dealing with an object, not array
print $siteLanguages -> searchprofiles;
The right way is this:
$siteLanguages = json_decode($result,true);
will get an array,your way get an object;