我是php的新手。我正在阅读RSS源并存储在我的数据库表中。 为此,我使用
$num = count($movies->channel->item);
for ($i=0; $i<=$num-1; $i++){
$tittle= $movies->channel->item[$i]->title."<br/>";
$link=$movies->channel->item[$i]->link."<br/>";
$image=$movies->channel->item[$i]->medium_image_url."<br/>";
$des=$movies->channel->item[$i]->description."<br/>";
$city=$movies->channel->item[$i]->city;
}
如何使用foreach循环显示所有数据?
答案 0 :(得分:1)
您可以echo
声明结果(我已根据要求将其更改为foreach
):
foreach ($movies->channel->item as $item) {
$tittle= $item->title."<br/>";
$link=$item->link."<br/>";
$image=$item->medium_image_url."<br/>";
$des=$item->description."<br/>";
$city=$item->city;
echo $tittle.$link.$image.$des.$city;
}
答案 1 :(得分:1)
foreach($movies->channel->item as $opt){
echo $tittle= $opt->title."<br/>";
echo $link=$opt->link."<br/>";
echo $image=$opt->medium_image_url."<br/>";
echo $des=$opt->description."<br/>";
echo $city=$opt->city;
}
答案 2 :(得分:1)
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city;
}
我已经回应了他们,因为我认为这是你想要做的事情 - 你的代码在每次迭代时重新分配变量,但对它们没有任何作用。它们每次都被覆盖,因此它们只保留最后一次迭代的值。
修改强>
您可以通过执行以下操作轻松修改此操作以将行插入数据库:
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES
('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
}
或者,您可以将其全部转换为一个查询,以最大限度地减少数据库流量:
$rows = array();
foreach ($movies->channel->item as $item) {
echo $item->title.'<br />';
echo $item->link.'<br />';
echo $item->medium_image_url.'<br />';
echo $item->description.'<br />';
echo $item->city.'<br />';
// Add this entry to $rows
$rows[] = "('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
}
// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
(`title`,`link`,`medium_image_url`,`description`,`city`)
VALUES ".implode(', ',$rows);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
答案 3 :(得分:1)
这应该有效:
foreach ($movies as $movie)
$tittle = $movie->title."<br/>";
$link = $movies->link."<br/>";
$image = $movie->medium_image_url."<br/>";
$des = $movie->description."<br/>";
$city = $movie->city;
}