Convert PHP json encoded UTF8 string into regular characters - php

I have a UTF8_encoded array in PHP (5.3) but can't seem to use manipulate the results in a normal way.
When echo'ing the data in PHP the results show up correctly but when testing the variable (eg using is_numeric) it fails.
How can I convert this array to make the data useable as normal in PHP?
getInfo($host,$port){
....
$prestore = mb_split("\xc2\xA7", utf8_encode($response));
return array( 'name' => $prestore[0],
'online_players' => $prestore[1],
'maximum_players' => $prestore[2]);
}
$data = getInfo($host,$port);
var_dump($data);
$data2 = json_encode(getInfo($host,$port));
echo $data2;
PHP Var dump of data results are correct but the string lengths are all off.
Array(3) {
["name"]=>
string(23) "MC-Outbreak"
["online_players"]=>
string(5) "13"
["maximum_players"]=>
string(4) "70"
}
PHP json_encode results look like this.
{"name":"\u0000M\u0000C\u0000-\u0000O\u0000u\u0000t\u0000b\u0000r\u0000e\u0000a\u0000k\u0000","online_players":"\u00001\u00003\u0000","maximum_players":"\u00007\u00000"}
I spent a couple hours trying different things but am completely stuck now! Any help would be appreciated.
Thanks.

Your text is in UTF-16BE. Use iconv to convert it to UTF-8 first.

return array( 'name' => utf8_decode($prestore[0]),
'online_players' => utf8_decode($prestore[1]),
'maximum_players' => utf8_decode($prestore[2]));
Try this

Related

encoded json array getting corrupted in cookie when trying to decode json

I will explain below exactly what is happening. Any thoughts on a fix would be great thanks.
See below my PHP array..
$myArray = array( 145 => true, 134 => true, 152 => true);
My array then var dumped..
array(3) { [145]=> bool(true), [134]=> bool(true), [152]=> bool(true) }
I then json encode my array..
$myJson = json_encode($myArray);
My encoded json var dumped result is..
string(34) "{"145":true,"134":true,"152":true}"
I then set my cookie using the json string like this..
setcookie('mycookie', $myJson);
Then this is the cookie contents after it has been set..
%7B%22145%22%3Atrue%2C%22134%22%3Atrue%2C%22152%22%3Atrue%7D
OK this where the trouble begins
I then get the cookie contents using this..
$myCookie = $_COOKIE['mycookie'];
This a var dump of $myCookie..
string(40) "{\"131\":true,\"134\":true,\"152\":true}"
As you can see this not the same string that I set in the cookie. There are now backslashes like its being escaped or something. Why is this happing?
If I try and decode the json now it returns NULL.
Can anyone understand why this is happening? Surely I shouldn't have to string replace these back slashes? All I want to do decode the json. My original encoded string decodes fine, its just when it's added to the cookie, it corrupts my json.

Expand an string based on values in an array in PHP

I would like to expand a string with one or more values which come from an array.
Desired result:
http://example.com/search/key=["Start", "USA", "Minneapolis"]&shift=false
Array:
array(2) {
[0]=>
string(8) "USA"
[1]=>
string(4) "Minneapolis"
}
PHP Code:
$myArr = ("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start",' .$myArr[0]. ']&shift=false';
Gives me this result: http://example.com/search/key=["Start", "USA"]&shift=false
How can I make it more dynamic so that more than one value can be added? I know I somehow have to use a foreach($myArr as $i){...} and concatenate the values via $string += but because my variable is in the middle of the string I'm kinda stuck with this approach.
Try the following:
$myArr = array("USA", "Minneapolis");
$string = 'http://example.com/search/key=["Start", "' . implode('", "', $myArr) . '"]&shift=false';
This will provide the expected output using implode.
Something isn't right here. You are trying to pass array data through a querystring but not in a valid array structure. This means you are either not using it as an array on the next script and you are going to having to chop and hack at it when the data gets there.
I'll make the assumption that you would like to clean up your process...
Declare an array of all of the data that you want to pass through the url's query string, then merge the new key values into that subarray. Finally, use http_build_query() to do ALL of the work of formatting/urlencoding everything then append that generated string after the ? in your url. This is THE clean, stable way to do it.
Code: (Demo)
$myArr = ["USA", "Minneapolis", "monkey=wren[h"];
$data = [
'key' => [
'Start'
],
'shift' => 'false'
];
$data['key'] = array_merge($data['key'], $myArr);
$url = 'http://example.com/search/?' . http_build_query($data);
echo "$url\n---\n";
echo urldecode($url);
Output:
http://example.com/search/?key%5B0%5D=Start&key%5B1%5D=USA&key%5B2%5D=Minneapolis&key%5B3%5D=monkey%3Dwren%5Bh&shift=false
---
http://example.com/search/?key[0]=Start&key[1]=USA&key[2]=Minneapolis&key[3]=monkey=wren[h&shift=false
*the decoded string is just to help you to visualize the output.
Then on your receiving page, you can simply and professionally access the $_GET['key'] and $_GET['shift'] data.
If you have a legitimate reason to use your original malformed syntax, I'd love to hear it. Otherwise, please use my method for the sake of clean, valid web development.

php, json to specific string

By POST I get this JSON (can have more than 3 values in it)
{"preferences":["Theater","Opera","Danse"]}
Well, I need to get
array('Theater', 'Opera', 'Degustation')
json_decode doesn't work.
Do you have any ideas please?
Thank you by advance
Try adding the true parameter:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true );
var_dump($arrayData['preferences']);
The last line outputs the following:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
Which is what you want. Good luck!
That JSON string is wrapped in an object (denoted by curly braces {}). json_decode will give you the wrapper object whose "preferences" property is the array you're looking for.
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
json_decode might also be unavailable if you're using and older version of php. In that case you should try a php json library.
You might have used the output of the json_decode() function as an associated array while you hadn't have told the function to provide an associated array for you, or vice versa!! However, the following will get you the array at the preferences index:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ( [0] => Theater [1] => Opera [2] => Danse )
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>

How to access json_decode parameters in PHP

So, i'm trying to access some input fields in a form which I get with
$data = json_encode($app->request->getBody());
It returns something like this after an echo $data:
"groupname=group13&description=description"
But I just can't figure out how to access those parameters, I've tried with
$data[0]
$data['groupname']
$data->groupname
How can I access to this array elements?
[UPDATE]
Tried all of your solutions, none of them worked for me :(
I've finally solved it using this since I only have 2 fields
$groupname = $app->request->post('groupname');
$description = $app->request->post('description');
That is not JSON, it's URL encoded text... Use parse_str() instead.
Friend, in this case if you really need to manage this final query string you can do:
$my_query = "groupname=group13&description=description";
explode elements into a assoc array using parse_str:
parse_str($my_query, $output);
var_dump of $output :
array(2) {
'groupname' =>
string(7) "group13"
'description' =>
string(11) "description"
}
you can remount your query string too using http_build_query:
var_dump(http_build_query($output));
string(41) "groupname=group13&description=description"
I hope this can help you.
Seems like you executed the serialize() method in jQuery
When you do a json_encode(), the output is like {"a":1,"b":2,"c":3,"d":4,"e":5}

associative array, json to php

In my php file im using the following,
$obj = ($_POST['data']);
var_dump(json_decode($obj,true));
And i see this result. Is this the correct format? and how do i access the array.
eg, set a new variable $newID the same as row1 id
array(4) {
["row0"]=>
string(92) "{"id":"157","name":"123","basic":"123123123","submitter":"Keith","status":"review"}"
["row1"]=>
string(169) "{"id":"158","name":"TEST RESOURCE","basic":"Please state the type of work.","submitter":"Keith","status":"review"}"
["row2"]=>
string(107) "{"id":"159","name":"TEST OTHER","basic":"testing for other","submitter":"Keith","status":"review"}"
["row3"]=>
string(160) "{"id":"160","name":"Name","basic":"type of work","submitter":"Keith","status":"review"}"
}
heres whats in POST in firebug
data {"row0":"{\"id\":\"157\",\"name\":\"123\",\"basic\":\"123123123\",\"submitter\":\"Keith\",\"status\":\"review\"}","row1":"{\"id\":\"158\",\"name\":\"TEST RESOURCE\",\"basic\":\"Please state the type of work.\",\"submitter\":\"Keith\",\"status\":\"review\"}","row2":"{\"id\":\"159\",\"name\":\"TEST OTHER\",\"basic\":\"testing for other\",\"submitter\":\"Keith\",\"status\":\"review\"}","row3":"{\"id\":\"160\",\"name\":\"Name\",\"basic\":\"type of work\",\"submitter\":\"Keith\",\"status\":\"review\"}"}
Each "row" of the array is another JSON string. It seems like the data was double-encoded, like:
$array = json_encode(
array(
'row0' => json_encode(array('id' => '157', ...)),
...
)
)
This is incorrectly encoded data, unless you wanted JSON objects inside JSON objects. To work with it, you need to json_decode each individual item again. Better though: fix the encoding step.

Categories