包含html标记时,JSON字段返回null

时间:2016-12-06 10:03:43

标签: php mysql json

我试图在包含HTML标记的表中公开一些数据,当我访问该页面时,所有不包含HTML的字段都很好,但任何包含html的字段都返回null。

我已尝试将字段设置为VarChar和Text,但似乎都不起作用。该表也设置为utf8_general_ci

request_step_content.php

<?php
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");

$user = "userName";
$pass = "userPassword";
$table = "myTable";

$db=new PDO("mysql:host=localhost;dbname=$table", $user, $pass);

$query = "SELECT * FROM steps";

try {
    $stmt = $db->query($query);
    }
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error.";
    die(json_encode($response));
}

$rows = $stmt->fetchAll();

if($rows) {
    $response["success"] = 1;
    $response["message"] = "Step";
    $response["step"] = array();

    foreach ($rows as $row) {
        $post = array();
        $post["id"] = $row["intID"];
        $post["heading"] = $row["strStepheading"];
        $post["keyPrinciple"] = $row["strKeyPrinciple"];
        $post["pillar"] = $row["strPillar"];
        $post["introduction"] = $row["memIntroduction"];
        $post["actionSteps"] = $row["memActionSteps"];
        $post["actionPoints"] = $row["memActionPoints"];
        $post["studyAndUnderstanding"] = $row["memStudyUnderstanding"];

        array_push($response["step"], $post);
    }
    echo json_encode($response);
}
else {
    $response["success"] = 0;
    $response["message"] = "No Steps Available";
    die(json_encode($response));
}
?>

json回复

{"success":1,
 "message":
           "Step",
           "step":[{"id":"1",
                          "heading":"Test Heading",
                          "keyPrinciple":"Key Principle: Test Key Principle",
                          "pillar":"Pillar 1: Pillar",
                          "introduction":null,
                          "actionSteps":null,
                          "actionPoints":null,
                          "studyAndUnderstanding":null}]}

2 个答案:

答案 0 :(得分:0)

问题在于编码。 DB表中的列可以是UTF-8,但存储的数据不必是UTF-8。 PHP函数json_encode只接受UTF-8数据。检查存储的数据库数据。

答案 1 :(得分:0)

我在@Fky关于编码的答案的帮助下解决了这个问题。

使用utf_encode()我现在拥有所有字段,包括我的JSON字段中的html内容。这是编辑过的代码:

        foreach ($rows as $row) {
        $post = array();
        $post["id"] = $row["intID"];
        $post["heading"] = $row["strStepheading"];
        $post["keyPrinciple"] = $row["strKeyPrinciple"];
        $post["pillar"] = $row["strPillar"];
        $post["introduction"] = utf8_encode($row["memIntroduction"]);
        $post["actionSteps"] = utf8_encode($row["memActionSteps"]);
        $post["actionPoints"] = utf8_encode($row["memActionPoints"]);
        $post["studyAndUnderstanding"] = utf8_encode($row["memStudyUnderstanding"]);

感谢您的帮助。