PHP json_decode给出空数组

时间:2016-05-27 14:46:17

标签: php json

您好我正在尝试将带有json格式的字符串解码为关联数组。字符串是这样的:(我的字符串来自数据库,并在那里生成)

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

当我做json_decode()时,它给了我一个空数组。你知道为什么会这样吗?我相信它来自“Parameter1”,但却无法找到它是什么。

谢谢:)

3 个答案:

答案 0 :(得分:1)

Akshay确实是正确的,它是由换行引起的。

<pre><?php

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

// json_decode($input, true);
// echo json_last_error_msg(); // Syntax error

$input = str_replace("\r", null, $input);
$input = str_replace("\n", null, $input);

var_dump(json_decode($input, true));

打印:

array(2) {
  ["Parameter1"]=> string(176) "<style>                  #label-9 {                  display: block;                  text-align: left;                  color: #fff;                  }                </style>"
  ["HistoryPosition"]=> string(1) "1"
}

答案 1 :(得分:1)

JSONLint表示JSON无效。

您可能想要做的是以下

$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));

演示https://3v4l.org/X6KgM

答案 2 :(得分:1)

除了手写您自己的JSON字符串外,您绝对应该使用PHP的内置函数,使您的喜欢至少483%:

// Use a native PHP array to store your data; it will preserve the new lines
$input = [
    "Parameter1" => "<style>
                  #label-9 {
                  display: block;
                  text-align: left;
                  color: #fff;
                  }
                </style>",
    "HistoryPosition" => "1"
];

// This function will preserve everything in your strings
$encoded_value = json_encode($input);

// See your properly formatted JSON string
echo $encoded_value.'<br><br>';

// Decode the string back into an associative PHP array
echo '<pre>';
print_r(json_decode($encoded_value, true));
echo '</pre>';

根据有关数据库检索的新信息进行更新

json_last_error_msg();产生此错误:

  

控制字符错误,可能编码错误

如果您不关心保留换行符,那么这将有效:

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

$db_data = str_replace("\r", "", $db_data);
$db_data = str_replace("\n", "", $db_data);

echo '<pre>';
print_r(json_decode($db_data, true));
echo '</pre>';
相关问题