I am having an issue decoding a JSON string with PHP and I’m pretty sure I know what is causing it, but not sure how to fix it. I am putting an array that I convert to JSON into a hidden textarea and then posting that with other information to my PHP script.
Here is a sample of the JSON string that is being placed into the text area: I am using $("#product_options").val(JSON.stringify(productOptions));
to place the JSON into the text box.
[{
"optionID": "217",
"optionValueID": ["3"]
}, {
"optionID": "218",
"optionValueID": ["5"]
}, {
"optionID": "223",
"optionValueID": ["8", "11"]
}, {
"optionID": "208",
"optionValue": ["test"]
}, {
"optionID": "209",
"optionValue": ["zxvsdfg"]
}, {
"optionID": "219",
"optionValue": ["2011-02-20"]
}, {
"optionID": "221",
"optionValue": ["22:25"]
}, {
"optionID": "220",
"optionValue": ["2011-02-20 22:25"]
}]
That decodes fine, but once I post it and read the value of the field in PHP using $_POST['json_array']
it will not decode. Below is the entire post converted to JSON:
{
"full_name": "sdfg",
"phone": "sdfg",
"email": "sdfg",
"notes": "sdgf",
"product_id": "42",
"product_options": "[{"
optionID ":"
217 ","
optionValueID ":["
3 "]},{"
optionID ":"
218 ","
optionValueID ":["
5 "]},{"
optionID ":"
223 ","
optionValueID ":["
8 ","
11 "]},{"
optionID ":"
208 ","
optionValue ":["
test "]},{"
optionID ":"
209 ","
optionValue ":["
zxvsdfg "]},{"
optionID ":"
219 ","
optionValue ":["
2011 - 02 - 20 "]},{"
optionID ":"
221 ","
optionValue ":["
22: 25 "]},{"
optionID ":"
220 ","
optionValue ":["
2011 - 02 - 20 22: 25 "]}]"
}
EDIT:
This is the PHP code I am using to decode the JSON $productOptions = json_decode($_POST['product_options']);
.
The error I receive is: Invalid argument supplied for foreach()
but that is because I am trying to loop through the array after its been converted from JSON.
Advertisement
Answer
Well after fighting with the code for 3 days I figured it out: json_decode or eval cannot handle ” which is how the quote was coming through in the post string, but it displayed as a ” in the browser when I did a variable dump so was very hard to debug. So to solve I added the code:
$_POST['product_options'] = str_replace('"', '"', $_POST['product_options']);
seems like a stupid PHP bug to me :{