Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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',
  ),
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading