如何从file_get_html($url)保存数据到数据库


How to save data to a database from file_get_html($url)?

我不能从file_get_html($url)函数保存数据到数据库。我的脚本通过抓取url很好地显示数据。但是我不能将显示的数据保存到数据库中。它显示了对象和数组之间的错误。我甚至不能通过数组索引来显示数据。例如$value[0]。下面是我的代码示例:

$con=mysqli_connect("localhost","root","","crawler");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
require 'simple_html_dom.php';
$url = "http://www.realestate.com.au/sold/in-perth/list-1";
//Address Collection
$html = file_get_html($url);
foreach ($html->find("h2") as $key => $value){
echo $value."<br>";
$result = mysqli_query($con,"INSERT INTO data (info) VALUES ('$value')");
if (!$result){
    echo "Error!<br>";
}
}
mysqli_close($con);
?>

试试这个,让我知道它是否有效:

$con=mysqli_connect("localhost","root","","crawler");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
require 'simple_html_dom.php';
$url = "http://www.realestate.com.au/sold/in-perth/list-1";
//Address Collection
$html = file_get_html($url);
foreach ($html->find("h2") as $key => $value){
echo $value."<br>";
}
$value = base64_encode($value);
$result = mysqli_query($con,"INSERT INTO data (info) VALUES ('$value')");
if (!$result){
    echo "Error!<br>";
}
mysqli_close($con);
?>

$value在写入数据库之前需要转换为字符串。可以使用

显示数组或对象

echo '<pre>'; print_r($value); echo '</pre>';

var_dump($value)