I am sending php array as json format, but I was unable to decode the value. Here is how I made the array
$ads = $atts['ads'];
if (sizeof($ads) > 0) {
foreach($ads as $social_item) {
$sdbr = $social_item['sidebar'];
$pno = $social_item['no'];
$out[$sdbr] = $pno;
}
}
Which output
array (
'Full width ad 1' => 2,
'sidebar-1' => 3,
)
Now I have json encode it
$myJSON = json_encode($out);
The json formatted value {"Full width ad 1":2,"sidebar-1":3}
Then I am passing it through data attribute value
echo "<div data-ad = '$myJSON' class='ash_loadmore'><span>LOAD MORE</span>
</div>";
The out that I have got
$ad = $_POST['ad'];
array (
'Full width ad 1' => '2',
'sidebar-1' => '3',
)
So now time for decode the output
$out = json_decode($ad,TRUE);
var_dump($out); // Returns NULL although the array value is present
But if I put the json format data it works fine
$out = json_decode('{"Full width ad 1":2,"sidebar-1":3}',TRUE);
var_dump($out);
I suspect before json encode the array array(2) { ["Full width ad 1"]=> int(2) ["sidebar-1"]=> int(3) }
value is int
but I am getting value as string
array(2) { ["Full width ad 1"]=> string(1) "2" ["sidebar-1"]=> string(1) "3" }
What's wrong doing by me?
After this step:
$ad = $_POST['ad'];
array (
'Full width ad 1' => '2',
'sidebar-1' => '3',
)
you see in the output that this is already a php array, so any json-decode method will fail (this is no json).
You can work with the array right away, depending what you want to do ;)
I think that putting serialized JSON in html attribute could cause you a problem.
The reason why it can cause the problem is because your JSON could contain characters like " or ' and it your output so it could corrupt your HTML syntax.
I guess you are sending that JSON via AJAX back to some PHP script, so reading JSON from corrupted HTML element could fetch invalid JSON data.
Solution to this problem is to use...
$myJSON = htmlentities($str, ENT_QUOTES);
... before outputing it into HTML. This will encode only quote characters.
You should also decode it on your PHP endpoint by using...
$ad = html_entity_decode($ad, ENT_QUOTES);
$out = json_decode($ad,TRUE);
Hope this helps.