我正在尝试获取url的内容并保存在mysql中,但我只能获取最后一个值
for($i = 1; $i < 5; $i++) {
$url = "http://something.php/$i";
$content = file_get_contents($url);
echo '<pre>';
print_r($content);
echo '</pre>';
}
答案 0 :(得分:1)
像这样追加$ content
$content .= file_get_contents($url);
答案 1 :(得分:1)
这可能适合你:
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'DATABASE_NAME';
$DB_HOST = 'DATABASE_HOST';
$DB_USER = 'DATABASE_USER';
$DB_PASS = 'DATABASE_PASSWORD';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
for($i = 1; $i < 5; $i++) {
$url = "http://something.php/$i";
$content = file_get_contents($url);
$query = "INSERT INTO `urls` (`url`,`html`) VALUES ('$url', '$content');";
if ( $mysqli->query($query) ) {
echo "A new entry has been added with the `id` of {$mysqli->insert_id}.";
} else {
echo "There was a problem:<br />$query<br />{$mysqli->error}";
}
}
/* close our connection */
$mysqli->close();
?>
备注:强>
确保使用相应的table
(urls
)和fields
(id, url, html
)
创建一个Mysql数据库:
CREATE TABLE `urls` (
`id` int NOT NULL AUTO_INCREMENT ,
`url` varchar(80) NOT NULL ,
`html` varchar(50000) NOT NULL
)
;
答案 2 :(得分:0)
您正在覆盖循环的每次迭代中的内容。根据您希望在mySQL中保存内容的方式,您需要执行以下两项操作之一:
创建项目数组的示例:
$contents = array();
for($i = 1; $i < 5; $i++) {
$url = "http://something.php/$i";
array_push($contents, file_get_contents($url));
echo '<pre>';
print_r($contents[$i-1]);
echo '</pre>';
}
现在你有一些你可以操纵的东西。