How to generate json using php? [duplicate]

I am using a plugin that requires data in the following JSON format:

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

How to generate a JSON output as above, using PHP?


Solution 1:

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.

Solution 2:

The simplest way would probably be to start with an associative array of the pairs you want:

$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");

then use a foreach and some string concatenation:

$jsontext = "[";
foreach($data as $key => $value) {
    $jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";

Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.

Solution 3:

You can use the stdClass, add the properties and json_encode the object.

$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;

echo '<pre>';var_dump( json_encode($object) , $object );die;

Voilà!

string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
  ["first_property"]=>
  int(1)
  ["second_property"]=>
  int(2)
}

Solution 4:

This is one of the most fundamental rules in php development:

DO NOT MANUALLY BUILD A JSON STRING. USE json_decode().

If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.

Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.

It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.

Code:

$array = [
    [
        'oV' => 'myfirstvalue',
        'oT' => 'myfirsttext'
    ],
    [
        'oV' => 'mysecondvalue',
        'oT' => 'mysecondtext'
    ]
];

echo json_encode($array);

Output:

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

For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.

Solution 5:

This is the php code to generate json format.

while ($row=mysqli_fetch_assoc($result))
{
    $array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead