post string and array using curl [duplicate] - php

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
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?

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.

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.

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.

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)
}

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

Related

PHP - retrieving and parsing this JSON file

I'm looking for a way to access this JSON file data. What I'm interested in is to extract the property named documentjsonblob, as below.
object(Quadrem\Model\Order)[201]
protected '_dateCreated' => null
protected '_buyerCode' => null
array (size=2)
2415 =>
array (size=23)
'#storeid' => string '813' (length=3)
'#active' => string '1' (length=1)
'#created' => string '2013-11-25 12:28:21' (length=19)
'documentjsonblob' => string '{"HEAD":{"ORDERSEQUENCE":"0","TOTAL_TAX":7.9,"TOTAL_AMOUNT":86.9,"NUMBER":"AKMon3","TYPE":"NB","TYPE_NAME":"Standard PO","SUPPLIER":"0000002122","CREATED":"2013-04-29T12:00:00Z","CONTRACT_NUMBER":"","EXTERNAL_REFERENCE":"","CONTACT_PERSON":"Caroline Howlett","COMMENT":[""],"CURRENCY":"AUD","DELIVERY_TERMS":"DeliveryCondition|","PAYMENT_TERMS":[{"TEXT1":"21st day of next month after receipt"}],"NET_VALUE":79.0,"DELIVERY_ADDRESS":{"NAME_1":"KGTP FACILITY","NAME_2":"GAS TREATMENT PLANT","NAME_3":"KGPF","POSTAL_CODE":"6714","CITY":"Karratha","STREET":"Withnell Bay","REGION":"AUWA","REGION_NAME":"AUWA","COUNTRY":"AU"}]}' (length=3029)
'documenttype' => string 'PO' (length=2)
1890 =>
array (size=23)
'#storeid' => null
'#active' => null
I'm not quite sure which kind of an encoded JSON file this is by the way it looks. Would appreciate it if somebody could help.
Thanks.
Since in the comment you have mentioned it is the out put of var_dump and you want to get documentjsonblob, let's follow this:
On first line you have object(Quadrem\Model\Order)[201], that means you var_dumped an object, say $my_obj
On line four array (size=2) says you have an array, and what you need is located in the first element of the array, so $my_obj[0]
$my_obj[0] holds an associative array, and the desired index is documentjsonblob, so we can get the String representation as:
$my_arr = $my_obj[0];
$json_str = $my_arr['documentjsonblob'];
Now $json_str holds the String representation, to convert it to an PHP object:
$json_obj = json_decode($json_str);
So now $json_obj holds the object you want.

Array manipulation

Hey I am stuck in the middle of my code. I am getting some input data from my partner and I get an array. At the 0 index of the array there are 3 strings. The array looks like this
array
0 =>
object(MunichInnovationGroup\PatentBundle\Entity\PatentIdJson)[1405]
private 'patentId' => string 'EP.02708872.A' (length=13)
private 'jsonData' => string '{"ops:world-patent-data": {
"#xmlns": {
"ops": "http://ops.epo.org",
"$": "http://www.epo.org/exchange",
"ccd": "http://www.epo.org/ccd",
"xlink": "http://www.w3.org/1999/xlink"
},
"ops:meta": {
"#name": "elapsed-time",
"#value": "69"
}
private 'status' => string 'Found' (length=5)
What I am interested in is the 'jsonData' String. Can I covert this whole array to a multidimensional array or just get the 'jsonData' and convert it into an array so that I get the information what I need from the 'jsonData'.
Thanks
what you need is json_decode and you can do the following:
$jsonObject = json_decode($myArray[0]->getjsonData(), true);
That will generate an object from the jsonData your partner is providing in the array
Based on your comment, you can get to the data using:
$jsonData = $your_array[0]->getjsonData();
Assuming that the MunichInnovationGroup\PatentBundle\Entity\PatentIdJson extends the MunichInnovationGroup\PatentBundle\Entity class.

How to use json and php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().

Prevent json_encode() from automatically generating integer keys

I'm trying to encode a two-dimensional PHP array to JSON with json_encode() and I'm having a problem:
My array looks like this:
$array = array( array( 1325368800, 6898 ) );
When I encode it to JSON using json_encode(), the output looks like this:
'data' : [
'0' : [ '0' : '1325368800', '1' : '6898' ]
]
I would like to get rid of the automatically generated integer keys and have it like this:
'data': [ [ '1325368800', '6898' ] ]
Any tips?
This can only happen if you give the JSON_FORCE_OBJECT flag to json_encode (live demo):
echo json_encode(array(array( 123, 123 )));
// outputs [[123,123]]
echo json_encode(array(array( 123, 123 )), JSON_FORCE_OBJECT);
// outputs {"0":{"0":123,"1":123}}
Make sure the second argument of json_encode is not set, or set to a value generated by ORing JSON_* constants together.
If, however, the data is an associative array, you can use array_values to get a JSON array instead of a JSON object:
$assocData = array('0' => array('0' => 123, '1'=>123));
$arrayData = array_map('array_values', array_values($assocData));
echo json_encode($arrayData);
By the way, the JSON output you cited is invalid, since it uses square brackets ([]) for objects, and misses a quote after "0.

Generate json string from multidimensional array data [duplicate]

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
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?
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.
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.
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.
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)
}
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

Categories