如何将HTML数据转换为json,php,mysql?

时间:2016-01-19 08:12:02

标签: php mysql json

如何将HTML数据转换为json,示例如下,描述内容如何转换为json,它是从mysql,php。,如何发送json响应为纯文本,但描述来自mysql db,因为它是,但如何将json响应api发送给androind。

public function actionTestanalysis()
{
//echo $keyword=$_POST['keyword'];
    $query= Yii::app()->db->createCommand("select * from test ORDER BY id DESC")->queryAll();
    $arr = array();
    if(count($query) > 0) {

    foreach($query as $query){
    $arr[] = $query;    
    }
    }

    # JSON-encode the response
    $json_response = json_encode($arr);

    // # Return the response
    echo $json_response;


//exit;
}

json回应

[
    {
        "id": "99",
        "name": "Max-Gain on or before 25th January 2016 in Max India Limited.",
        "description": "
\r\n\tMax India Limited has announced the Record date for Three way De-Merger as 28th January 2016 (Thursday). <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tAnyone want to Gain from the three way De-Merger of Max India Group one should buy the shares of Max India Limited on or before – 25th January 2016 (Cum-Date – Monday Tentavily) otherwise to be on safer side you can buy on or before 22nd January 2016(Friday) and get invested in it.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tIf any investor invests for a period Of 12 – 18 Months , this scrip will be a Multifold - Multi Bagger.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tTo View the full report on Max India Limited authored . <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tPlease Click The Below Link<\/div>\r\n
\r\n\t

\r\n\t\thttp:\/\/www.test.com\/index.php\/newsOpportunities\/list\/scroll\/no-pain-all-gain-maximum-benefit-in-max-india-ltd<\/a><\/p>\r\n<\/div>\r\n",
        "image": "",
        "status": "unlock"


    },

3 个答案:

答案 0 :(得分:0)

您的代码中的循环中也有一个错误。

试试这个:

if (count($query) > 0) {
    foreach ($query as $queryElement) {
        $el = $queryElement;
        $el['description'] = trim(preg_replace('/\s+/', ' ', strip_tags($el['description'])));
        $arr[] = $el;
    }
}

答案 1 :(得分:0)

尝试之前:echo $ json_response将标题内容类型设置为application / json

<?PHP
header('Content-Type: application/json');
echo $json_response;

答案 2 :(得分:0)

使用htmlentities()代替strip_tags(),以保留存储在db中的实际内容。