Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate json using php? [duplicate]

Tags:

json

php

I am using a plugin that requires an array of associative rows as a json formatted string -- something like:

[     {oV: 'myfirstvalue', oT: 'myfirsttext'},     {oV: 'mysecondvalue', oT: 'mysecondtext'} ] 

How do I convert my multidimensional array to valid JSON output using PHP?

like image 864
Haluk Avatar asked Sep 16 '09 19:09

Haluk


1 Answers

Once you have your PHP data, you can use the json_encode function; it's bundled with PHP since PHP 5.2.

In your case, your JSON string represents:

  • a list containing 2 elements
  • each one being an object, containing 2 properties/values

In PHP, this would create the structure you are representing:

$data = array(     (object)array(         'oV' => 'myfirstvalue',         'oT' => 'myfirsttext',     ),     (object)array(         'oV' => 'mysecondvalue',         'oT' => 'mysecondtext',     ), ); var_dump($data); 

The var_dump gets you:

array   0 =>      object(stdClass)[1]       public 'oV' => string 'myfirstvalue' (length=12)       public 'oT' => string 'myfirsttext' (length=11)   1 =>      object(stdClass)[2]       public 'oV' => string 'mysecondvalue' (length=13)       public 'oT' => string 'mysecondtext' (length=12) 

And, encoding it to JSON:

$json = json_encode($data); echo $json; 

You get:

[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}] 

By the way, from what I remember, I'd say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects' properties.

See http://www.json.org/ for the grammar.

like image 115
Pascal MARTIN Avatar answered Sep 25 '22 08:09

Pascal MARTIN