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

时间:2014-05-17 11:49:27

标签: php arrays object dom web-scraping

我无法从file_get_html($ 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);
?>

2 个答案:

答案 0 :(得分:0)

$ value需要在写入DB之前转换为字符串。您可以显示数组或对象使用

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

var_dump($value)

答案 1 :(得分: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>";
}
$value = base64_encode($value);
$result = mysqli_query($con,"INSERT INTO data (info) VALUES ('$value')");
if (!$result){
    echo "Error!<br>";

}
mysqli_close($con);
?>