PHP json_decode + Print Array Values Fails - php

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;

Related

How to echo the post value received in post

I'm using image uploader plugin which is posting data in multi dimension array like shown below
Array
(
[file] => {"input":{"name":"KE6Cc2ea2b584.jpg",
"type":"image/jpeg",
"size":61224,
"width":800,
"height":643},
"output":{"width":320,"height":180,
"image"
:"data:image/jpeg;base64,/9j/just an example of base 64 encoded image"},
"actions":{"crop":{"x":0,"y":96.5,"height":450,"width":800 },
"size":{"width":320,"height":320}}}
)
Now i tried lot to echo these post values like shown below
echo $_POST['file']; worked but brought all the data
echo $_POST['file']['output']; didn't worked
echo $_POST['file']['output']['image']; didn't worked
How can i get the value of these post
When trying to echo out any sort of values while debugging, it's a good idea to see exactly what you're getting via var_dump. For example, instead of your echo lines, I'd simply put:
echo "<pre>";
var_dump($_POST['file']);
Check your output there and it should show you exactly what keys you have to work with.
Also, depending on how your plugin is sending the data, you may not get any actual keys. According to your comment about $_POST['file'] printing all the output, it seems as though it's still a string. Try putting the JSON into an object, like so:
$test = json_decode($_POST['file']);
Or, if you'd prefer an associative array as mentioned:
$test = json_decode($_POST['file'], true);
Then get the output of $test:
echo "<pre>";
var_dump($test);

display data from an array in json form

i got an array from echo $posts
Array
(
[0] => Array
(
[id] => 14
[name] => اسطنبوليه
)
)
i have this array (part of the main array)and now i wish to convert it to json form. however i am not able to do so, i tried to convert the data through
echo json_encode ($posts);
but instead of original data i am getting an output u0627u0633u0637u0646u0628u0648u0644u064au0647n
can anyone tell how i can get the correct form
Please try echo json_encode($posts,JSON_UNESCAPED_UNICODE) (php 5.4 and above)
2 things. Firstly view source of the output in the browser and you should see it as a JSON encoded string rather than the interpreted version.
Secondly it looks like there is some character encoding issues as the string you're getting back is unicode. Make sure you have the encoding set right on your server and browser.

php read list from website into array

I have a list of products codes that i wish to read into an array using php.
the list is to be fetched from a website and has over 700 items looks something like this:
4310ABC
4590DEF
8950GHK
What i want to do is put every code into a php array like so:
php_array ( [0] => 4310ABC
[1] => 4590DEF
[2] => 8950GHK)
This is what i have:
$php_array = file_get_contents('http://anysite.net/product_codes.php');
print_r (explode("\n",$php_array));
But my result is :
Array ( [0] => 4310ABC
4590DEF
8950GHK)
I have tried explode, preg_split('/[\n\r]+/', $php_array); but nothing seems to do the trick. Can anyone give me some pointers? thanks!
The lines are separated by a br, so use this instead:
$php_array = file_get_contents('http://anysite.net/product_codes.php');
print_r (explode("<br>",$php_array));
Don't forget to change the br to however it's spelled within the document you are fetching, for example it's often spelled like this:
<br />
Which is the most correct way to write it.
It would depend how your php file is echoing out the three values, so I am not sure how it is interpreting line breaks. Try echoing out the values with no line breaks, but separated by some other character like '*' or something, and then explode them along that and see if that works.

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>

Why is json_encode adding backslashes?

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

Categories