簡體   English   中英

SQL表中的JSON編碼-> JSON問題

[英]JSON Encoding from SQL table -> JSON issue

我正在做一個學校作業,我必須將Twitter轉儲作為SQL並將其另存為JSON(用於D3)。 但是,我在JSON編碼方面遇到了一些問題。 我能夠正確獲取日期,用戶,轉發,收藏夾,以使所有功能正常運行,但是由於某種原因,該推文的實際文本僅編碼為“文本”。 我檢查了表格,那里的所有內容看起來都正確,但是由於某種原因,我的編碼器無法正確編碼文本。 這是我必須將Twitter SQL表編碼為JSON的代碼:

<?php
$dsn = 'mysql:host=localhost;dbname=twitter';
    define('MYSQL_USER','root');
    define('MYSQL_PASS','dismypassword');

$tweets = "SELECT `id`,`date`,`screen_name`,`favorite_count`,`favorited`,'text' as 'textThing' FROM tweets";

$sql = $tweets;

header("Content-Type: application/json");

try {
    $db = new PDO($dsn, MYSQL_USER, MYSQL_PASS);
    $statement = $db->prepare($sql);
    $statement->execute();
    $data = array();
    while ( ($row = $statement->fetch(PDO::FETCH_ASSOC)) ) {
        $data[] = $row;
    }
    echo json_encode($data);  
} catch (PDOException $e) {
    die('Query failed: ' . $e->getMessage());
}

?>

這樣的輸出將生成一個看起來像這樣的JSON文件(其中文本以簡單的“ text”形式出現:

[

{
id: "704419321326510080",
date: "2016-02-29 22:33:48",
screen_name: "cscstars",
favorite_count: "0",
favorited: "0",
textThing: "text"
},

{
id: "704419329287331840",
date: "2016-02-29 22:33:50",
screen_name: "Wary12",
favorite_count: "0",
favorited: "0",
textThing: "text"
},

{
id: "704419365588865024",
date: "2016-02-29 22:33:58",
screen_name: "lgib15",
favorite_count: "0",
favorited: "0",
textThing: "text"
},

{
id: "704419366243151874",
date: "2016-02-29 22:33:59",
screen_name: "jacqui4peace",
favorite_count: "0",
favorited: "0",
textThing: "text"
},

我找到了問題的根源。 根本不是JSON編碼器,而是導致功能失敗的tweet文本中的特殊字符。 在清理了tweet sql表后,該功能運行良好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM