我有一个mysql数据库,我需要其内容的RSS源。 我在json中要求相当于这个:
mysql_select_db("mydb", $con);
$result = mysql_query("select date, title, description, url from blah where type = 'OFFERS' order by ref desc");
echo '<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title></title>
<description></description>
<link></link>';
while($row = mysql_fetch_array($result))
{
echo "
<item>
<title>" . $row['title'] . "</title>
<description>" . $row['description'] . "</description>
<link>" . $row['url'] . "</link>
<image>" . $row['date'] . "</image>
</item>";
}
到目前为止,我最接近工作的是:
<?php
$host="localhost";
$username="username";
$password="password";
$db_name="mydb";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select date, title, description, url from blah where type = 'OFFERS' order by ref desc";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['title'][]=$row;
}
}
mysql_close($db_name);
echo json_encode($json);
?>
任何帮助将不胜感激
答案 0 :(得分:1)
while ($row = mysql_fetch_assoc($result)) {
$json[] = $row;
}
echo json_encode($json);
答案 1 :(得分:1)
由于mysql_fetch_row返回两个数组键和索引,因此最好使用mysql_fetch_assoc。这只会返回键。
此外,您正在获取项目,而不是标题。因此,请使用$json['items']
代替$json['title']
。
除此之外,rss中还有其他信息。您也可以在$json
中添加它们。
结果代码为,
$json=array();
$json['title'] = 'My JS/RSS';
$json['link'] = "http://". $_SERVER['HTTP_HOST']. $_SERVER["REQUEST_URI"];
$json['description'] = "";
$json['itmes'] = array();
while($row=mysql_fetch_assoc($result)){
$json['items'][]=$row;
}