rss和json php脚本从mysql中提取数据

时间:2018-04-11 12:08:43

标签: php json xml rss

我有一个带数据的sql数据库,想创建2个php脚本来输出rss格式和json格式的数据,但是我被卡住了,因为代码有问题......我想。我也希望分别被全球公认为rss和json格式。以下是我已经拥有的两组代码......

对于rss / xml ...

<?php
    header("Content-Type: application/rss+xml; charset=ISO-8859-1");
/* Define db credentials */ 
    $DBHOST = "localhost";
    $DBUSER = "1";
    $DBPASS = "2";
    $DBNAME = "3";
    $rssfeed = '<?xml version="1.0" encoding="ISO-8859-1"?>';
    $rssfeed .= '<rss version="2.0">';
    $rssfeed .= '<channel>';
    $rssfeed .= '<title>RSS Feed</title>';
    $rssfeed .= '<link>http://www.123.net</link>';
    $rssfeed .= '<description>RSS Feed</description>';
    $rssfeed .= '<language>en-us</language>';
    $rssfeed .= '<copyright>Copyright (C) 2018 123.net</copyright>';
/* connect to the db */
   $conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
if ($conn->connect_error) { trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR); }
mysqli_set_charset($conn,"utf8");
    $sql = "SELECT * FROM table ORDER BY updated_at DESC LIMIT 5";
$rs = $conn->query($sql);
if ($rs === false) { trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR); } else { $row_num = $rs->num_rows; }
$rssfeed .= '<item>';
        $rssfeed .= '<title>' . $title . '</title>';
        $rssfeed .= '<desc>' . $desc . '</desc>';
$rssfeed .= '</item>';
    } 
    $rssfeed .= '</channel>';
    $rssfeed .= '</rss>';
    echo $rssfeed;

对于json ......

<?php
/* Define db credentials */ 
    $DBHOST = "localhost";
    $DBUSER = "1";
    $DBPASS = "2";
    $DBNAME = "3";
/* connect to the db */
   $conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
if ($conn->connect_error) { trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR); }
mysqli_set_charset($conn,"utf8");
    $query= "Select * from table ORDER BY updated_at DESC LIMIT 5";
    $result = mysql_query($query) or die ("Could not execute query");
    while ($row = mysql_fetch_array($result)) {
        extract($row);
    }
    header('Content-Type:Application/json');
    echo json_encode($array);
    mysql_free_result($result);
    mysql_close($conn);
 ?>

1 个答案:

答案 0 :(得分:0)

请试试这段代码:

$jsonResult = [];

while ($row = mysqli_fetch_array($result)) {
    $jsonResult[] = $row;
}

header('Content-Type:Application/json');
echo json_encode($jsonResult);