What I want to do is the following:
- taking JSON as input from text area in php
- use this input and convert it to JSON and pass it to php curl to send request.
this m getting at php from get of api this json string i want to pass to json but it is not converting to array
echo $str='{
action : "create",
record: {
type: "n$product",
fields: {
n$name: "Bread",
n$price: 2.11
},
namespaces: { "my.demo": "n" }
}
}';
$json = json_decode($str, true);
the above code is not returning me array.
i think this should Work, its just that the Keys should also be in double quotes if they are not numerals.
If you are getting the JSON string from the form using
$_REQUEST
,$_GET
, or$_POST
the you will need to use the functionhtml_entity_decode()
. I didn't realize this until I did avar_dump
of what was in the request vs. what I copied into andecho
statement and noticed the request string was much larger.Correct Way:
With Errors:
Use
json_decode($json_string, TRUE)
function to convert the JSON object to an array.Example:
NOTE: The second parameter will convert decoded JSON string into an associative array.
===========
Output:
If you are getting json string from URL using
file_get_contents
, then follow the steps:your string should be in the following format:
Output:
If you ever need to convert JSON file or structures to PHP-style arrays, with all the nesting levels, you can use this function. First, you must json_decode($yourJSONdata) and then pass it to this function. It will output to your browser window (or console) the correct PHP styled arrays.
https://github.com/mobsted/jsontophparray