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


How to convert HTML data to json, php, mysql?

如何将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"

    },

在代码的循环中还有一个错误。

试试这个:

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

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

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

使用 htmlentities() 而不是 strip_tags() ,以保留存储在数据库中的实际内容。