2015-04-05 48 views
0

我正在使用簡單的html dom刮取數據。然而,似乎有一些奇怪的行爲。即使寫入測試6次,它也只添加3條記錄。它是如何循環6次,只增加3行?循環6次,但只添加3條記錄

include('simple_html_dom.php'); 

$html = file_get_html("http://www.dailydot.com/tags/counter-strike/"); 

foreach($html->find("//li[@class='span4']") as $element) { 
    echo "test"; 
    $title = strip_tags($element->find("//a[@class='article-title']/h3", 0)); 
    $img = $element->find("//div[@class='picfx']/a/img[@class='lzy-ld']", 0)->getAttribute('data-original'); 
    $link = $element->find("//a[@class='article-title']", 0)->href; 
    $date = $element->find("//p[@class='byline']/time", 0)->datetime; 
    mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')"); 
} 
+0

你可能想要在循環之前確認var_dump($ html-> find(「// li [@ class ='span4']」))以確認它實際上是循環了6個元素。此外,你可能想檢查任何mysqli錯誤。此外,您的查詢並不安全。您需要正確地轉義您的變量。 – arothuis 2015-04-05 23:31:09

+0

謝謝!將不勝感激,如果你作出回答:) – 2015-04-05 23:42:31

回答

1

可能是因爲它失敗了3次:D插入件不是注射安全的。你應該使用real escape string。如果你的代碼不會失敗,如果你的任何變量包含一個簡單的引號。 (它允許一個壞人注入sql命令)

include('simple_html_dom.php'); 

$html = file_get_html("http://www.dailydot.com/tags/counter-strike/"); 

foreach($html->find("//li[@class='span4']") as $element) { 


$title = mysqli_real_escape_string($con, strip_tags($element->find("//a[@class='article-title']/h3", 0))); 
$img = mysqli_real_escape_string($con, $element->find("//div[@class='picfx']/a/img[@class='lzy-ld']", 0)->getAttribute('data-original')); 
$link = mysqli_real_escape_string($con, $element->find("//a[@class='article-title']", 0)->href); 
$date = mysqli_real_escape_string($con, $element->find("//p[@class='byline']/time", 0)->datetime); 
mysqli_query($con, "INSERT INTO news (`title`, `url`, `image_url`, `news_text`, `referer_img`) VALUES ('$title', '$link', '$img', '$full_text_strip', 'test')"); 
    echo "test ".mysqli_error($con); 
} 
+0

你能舉個例子嗎? – 2015-04-05 23:41:29

+0

編輯:添加mysqli_real_escape_string並顯示最後一個sql錯誤。 (如果有) – mathieu 2015-04-05 23:52:38

+0

它無法找到與mysqli_real_escape_string變量?當我回應它們時,什麼都沒有出來 – 2015-04-06 09:39:09

相關問題