It seems that your form submits a json object to the server so use json_decode with second parameter set to true to convert it to an array.
$php_array= json_decode($_POST["questionandanswers"],true)
Answer from Osama on Stack OverflowHow to use the
Convert JSON Array to PHP Array Online for free?
What is PHP Array format?
How to convert JSON to PHP online?
It seems that your form submits a json object to the server so use json_decode with second parameter set to true to convert it to an array.
$php_array= json_decode($_POST["questionandanswers"],true)
Use json_decode like json_decode($json). It will return an object.
If you want array, use json_decode($json, true).
See: https://www.php.net/manual/en/function.json-decode.php
Is this what you are trying to achieve?
$incoming is the jsonString coming from the javascript code
$incoming = '{
"name":"A Name",
"_typography": {
"color": {
"hex":"#2196f3"
},
"text-transform":"uppercase",
"font-weight":"600"
}
}';
$a = json_decode($incoming, true);
echo var_export($a);
RESULT
array (
'name' => 'A Name',
'_typography' =>
array (
'color' =>
array (
'hex' => '#2196f3',
),
'text-transform' => 'uppercase',
'font-weight' => '600',
),
)
Only changes are that you should add true to json_decode and use var_export to get the php array string. If you wanted to get square bracket you could write some custom string generator code.
function convert_js_object_to_php() {
// Getting the JS object
$object = $request->get_header('js_object');
// Decoding it to a PHP object
$output = json_decode($object, true);
if ($output) {
return var_export($output, true);
}
return false;
}
I had to reformat your JSON which was not valid (checked on https://jsonlint.com/).
I voluntarily used multiple str_replace() so you better understand the process, however you can optimize the code below by making multiple replacements at the same time within the same str_replace().
This works:
<?php
$to_decode = "var BASE_DATA = {
userInfo: {
id: 0,
userName: 'no-needed',
avatarUrl: 'no-needed',
isPgc: false,
isOwner: false
},
headerInfo: {
id: 0,
isPgc: false,
userName: 'no-needed',
avatarUrl: 'no-needed',
isHomePage: false,
crumbTag: 'no-needed',
hasBar: true
},
articleInfo:
{
title: 'needed',
content: 'needed',
groupId: 'needed',
itemId: 'needed',
type: 1,
subInfo: {
isOriginal: false,
source: 'needed',
time: 'needed'
},
tagInfo: {
tags: [{\"name\":\"no-needed 1\"},{\"name\":\"no-needed 2\"},{\"name\":\"no-needed 3\"}],
groupId: 'no-needed',
itemId: 'no-needed',
repin: 0,
},
has_extern_link: 0,
coverImg: 'no-needed'
},
commentInfo:
{
groupId: 'no-needed',
itemId: 'no-needed',
comments_count: 151,
ban_comment: 0
},};";
/* Clean JSON and encapsulate in brackets */
$to_decode = str_replace('var BASE_DATA = {', '', $to_decode);
$to_decode = '{'.substr($to_decode, 0, -3).'}';
/* Remove spaces, tabs, new lines, etc. */
$to_decode = str_replace(' ', '', $to_decode);
$to_decode = str_replace("\n", '', $to_decode);
$to_decode = str_replace("\t", '', $to_decode);
$to_decode = str_replace("\r", '', $to_decode);
/* Encapsulate keys with quotes */
$to_decode = preg_replace('/([a-z_]+)\:/ui', '"{$1}":', $to_decode);
$to_decode = str_replace('"{', '"', $to_decode);
$to_decode = str_replace('}"', '"', $to_decode);
$to_decode = str_replace('\'', '"', $to_decode);
/* Remove unecessary trailing commas */
$to_decode = str_replace(',}', '}', $to_decode);
echo '<pre>';
var_dump(json_decode($to_decode));
Result using print_r :
(I added true/false for clarity, these will only show using var_dump() otherwise)
stdClass Object
(
[userInfo] => stdClass Object
(
[id] => 0
[userName] => no-needed
[avatarUrl] => no-needed
[isPgc] => false
[isOwner] => false
)
[headerInfo] => stdClass Object
(
[id] => 0
[isPgc] => false
[userName] => no-needed
[avatarUrl] => no-needed
[isHomePage] => false
[crumbTag] => no-needed
[hasBar] => true
)
[articleInfo] => stdClass Object
(
[title] => needed
[content] => needed
[groupId] => needed
[itemId] => needed
[type] => 1
[subInfo] => stdClass Object
(
[isOriginal] => false
[source] => needed
[time] => needed
)
[tagInfo] => stdClass Object
(
[tags] => Array
(
[0] => stdClass Object
(
[name] => no-needed1
)
[1] => stdClass Object
(
[name] => no-needed2
)
[2] => stdClass Object
(
[name] => no-needed3
)
)
[groupId] => no-needed
[itemId] => no-needed
[repin] => 0
)
[has_extern_link] => 0
[coverImg] => no-needed
)
[commentInfo] => stdClass Object
(
[groupId] => no-needed
[itemId] => no-needed
[comments_count] => 151
[ban_comment] => 0
)
)
thank @Bruno Leveque for your idea.
I edited your code like below so that it run well:
I changed
$to_decode = str_replace(' ', '', $to_decode);to$to_decode = preg_replace('/[\n| |\s]{2,}/',' ',$to_decode);, that means all 1+ space will be changed to 1 space. because sometimes we need space, like: content: 'I added
$to_decode = str_replace("'", '"', $to_decode);before your comment code/* Encapsulate keys with quotes */changed
$to_decode = preg_replace('/([a-z_]+)\:/ui', '"{$1}":', $to_decode);to$to_decode = preg_replace('/([a-z_]+)\: /ui', '"$1":', $to_decode);(one more space there); and commented//$to_decode = str_replace('"{', '"', $to_decode);and//$to_decode = str_replace('}"', '"', $to_decode);added one more code:
$to_decode = str_replace(", }", '}', $to_decode);
so my final code is :
because @Bruno Leveque does not know the exactly content of "needed" and "no-needed", so thank you for idea.
seems no perfect way....
Post your javascript array as a JSON string via ajax and process it server-side.
Javascript
var str_array = ["aa", "bb"];
var request = $.ajax({
url: "test.php",
method: "POST",
data: { myData : JSON.stringify(str_array) },
dataType: "html"
});
request.done(function( msg ) {
// ajax response
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
PHP (test.php)
$json = $_POST['myData'];
$myDataArray = json_decode($json,true);
print_r($myDataArray);
Eval() should end with ;
<?php
$str = 'var str_array = ["aa", "bb"]';
$str = str_replace("var ", '$', $str);
eval($str.";");
print_r($str_array);
Output:
Array ( [0] => aa [1] => bb )
But I don't know why you opt for this.
I'm going to assume that the two arrays you've given for PHP and JS are not related, and they're just examples of how arrays look in the two languages. Clearly you're not going to be able to convert those sequences of letters and numbers into those city names.
PHP provides a function to convert PHP arrays into Javascript code: json_encode(). (technically, it's JSON format; JSON stands for JavaScript Object Notation)
Use it like this:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
See also the manual page I linked above for more information.
Note that json_encode() is only available in PHP 5.2 and up, so if you're using an older version, you'll need to use an existing one -- the PHP manual page also includes comments with functions written by people who needed it. (but that said, if you're using anything older than PHP 5.2 you should upgrade ASAP)
Spudley's answer is fine.
Security Notice: The following should not be necessary any longer for you
If you don't have PHP 5.2 you can use something like this:
function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
echo 'var cities = ', js_array($php_cities_array), ';';