patricia patricia - 6 months ago 35
JSON Question

PHP json_decode gives empty array

Hi I'm trying to decode a string with json format into a associative array. The string is this one: (My string is from a database and its generated there)

{
"Parameter1":"<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition":"1"
}


And when I do
json_decode()
it gives me an empty array. Do you know why this happens? I believe it's something from the "Parameter1" but can't find what it is.

Thank you :)

Answer

JSONLint indicates the JSON is invalid.

What you might want to do is the following

$json = '{ 
  "Parameter1":"<style>
                  #label-9 {
                  display: block;
                  text-align: left;
                  color: #fff;
                  }
                </style>", 
  "HistoryPosition":"1"
}';
// remove the newlines
$clean = str_replace(["\r", "\n"], ['', ''], $json);
var_dump(json_decode($clean));

Demo https://3v4l.org/X6KgM