Home > database >  How to convert a JavaScript object to a PHP array and get the raw string?
How to convert a JavaScript object to a PHP array and get the raw string?

Time:09-09

In my application I need to convert a JavaScript Object to a raw PHP array returned as text string. I would do this calling an API. I don't need to manupulate the array. In my JavaScript application, I just need the plain PHP object string as showed below. (Like using this: https://wtools.io/convert-js-object-to-php-array)

The JavaScript object is:

{
"name":"A Name",
"_typography": {
  "color": {
    "hex":"#2196f3"
  },
  "text-transform":"uppercase",
  "font-weight":"600"
  }
}

How I send the JavaScript Object to the PHP function

JSON.stringify(jsObject);

What I need as string output:

[
"name" => "A Name",
"_typography" => [
  "color" => [
    "hex" => "#2196f3"
  ],
  "text-transform" => "uppercase",
  "font-weight" =>"600"
  ]
]

What I tried is to first json_decode the JavaScript object to a PHP object and then try to return it as a plain string back. But no chance. Either I get a Js Object back or something else entirely. I have no more ideas.

My try

function convert_js_object_to_php(WP_REST_Request $request) {

    // Getting the JS object
    $object = $request->get_header('js_object');

    // Decoding it to a PHP object
    $output = json_decode($object);

    if ($output) {
        return strval($output);
        // return $output (Here I also get the JavaScript object again)
        // return implode($output) (I don't get the plain PHP array)
    }

    return false;
}

Do you have any idea?

CodePudding user response:

Is this what you are trying to achieve?

$incoming is the jsonString coming from the javascript code

$incomming = '{
    "name":"A Name",
    "_typography": {
      "color": {
        "hex":"#2196f3"
      },
      "text-transform":"uppercase",
      "font-weight":"600"
      }
    }';

$a = json_decode($incomming, true);
echo var_export($a);

RESULT

array (
  'name' => 'A Name',
  '_typography' => 
  array (
    'color' => 
    array (
      'hex' => '#2196f3',
    ),
    'text-transform' => 'uppercase',
    'font-weight' => '600',
  ),
)

CodePudding user response:

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;
}
  • Related