使用PHP / MySQL创建JSON数据的正确方法

前端之家收集整理的这篇文章主要介绍了使用PHP / MySQL创建JSON数据的正确方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据以下答案更新:

根据以下答案,我现在有以下PHP脚本:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = MysqL_connect('server','user','pass') or die (MysqL_error());
    $db = MysqL_select_db('db_name',$connection) or die (MysqL_error());

    $results = MysqL_query($the_query) or die(MysqL_error());

    header('Content-type:application/json');

    $the_data['RSS']['channels']['title'] = $title;
    $the_data['RSS']['channels']['link'] = $link;
    $the_data['RSS']['channels']['description'] = $description;

    while($row = MysqL_fetch_array($result))
    {
        extract($row);

        $the_data['RSS']['channels']['items']['title'] = $item_title;
        $the_data['RSS']['channels']['items']['link'] = "$item_link;
        $the_data['RSS']['channels']['items']['date'] = $item_date;
        $the_data['RSS']['channels']['items']['description'] = $item_description;
    }   

    MysqL_close($connection);

    return json_encode($the_data);
}

返回以下内容

{
    "RSS":
    {
        "channels":
        {
            "title":"title goes here","link":"link goes here","description":"description goes here","items":
            {
                "title":"'title goes here","date":"date goes here","description":"description goes here"
            }
        }
    }
}

它应该根据从数据库返回的行数返回许多项目,为什么我只获得1项?

试试这个:
<?PHP
$channel = array(
     'title' => 'title goes here','link' => 'link here','description' => 'description','items' => array()
);
while($row = MysqL_fetch_array($results))
{
    extract($row);
    $channel['items'][] = array(
        'title' => $title,'link' => $link,'guid' => $guid,'pubDate' => $date,'description' => $description
    );
}   
$channels = array($channel);
$RSS = (object) array('RSS'=> array('channels'=>$channels));
$json = json_encode($RSS);
echo $json;

?>
原文链接:https://www.f2er.com/php/137593.html

猜你在找的PHP相关文章