2016-12-06 106 views
0

我想在包含HTML標記的表中公開一些數據,當我訪問頁面時,所有不包含HTML的字段都可以,但任何包含html的返回null。當包含html標記時,返回null的JSON字段

我曾嘗試將字段設置爲VarChar和文本,但都沒有工作。該表格也設置爲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}]} 
+0

使用htmlentities函數http://php.net/manual/fr/function.htmlentities.php對包含html的$行,您可以使用json_encode上的選項來完成查看http://php.net/的選項部分詳細信息manual/en/function.json-encode.php – Fky

+0

我實現了html實體,並將字段從null更改爲空。我不是100%的我應該用json_encode選項做什麼? – geolaw

回答

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"]); 

謝謝你的幫助所有。

+0

很高興知道:) – Fky

0

的問題將在編碼。數據庫表中的列可以是UTF-8,但存儲的數據不必使用UTF-8。 PHP函數json_encode只接受UTF-8數據。檢查你存儲的DB數據。

+0

謝謝!你把我放在答案上,將數組元素包裝在'utf_encode($ string)'中,現在所有的東西都可以使用! – geolaw

+0

請標記爲已回答。謝謝。 – sajushko