【问题标题】:Can not Insert foreach loop values into mysql table无法将 foreach 循环值插入 mysql 表
【发布时间】:2014-09-18 07:41:39
【问题描述】:

我从另一个网站上抓取日期,然后将所有获取值插入到我的表 sracp-data 中。我的值插入成功,但只插入最后一个值。

我的 Fetching 值如下所示:

My Fetching Cood:我用于使用 SIMPLE HTML DOM

抓取数据
            include './simple_html_dom.php';       //Inlcude HTML DOM
            $html = file_get_html('http://tacticalwalls.com/shop/');  //Scrapping site/url
              //**ul[class=products] here is specific DIV values** 
            foreach ($html->find('ul[class=products]') as $items) {
                foreach ($items->find('a') as $anchor) {          
                    $item_a = $anchor->href;
                }
                foreach ($items->find('img') as $img){
                    $item_img = $img->src;
                }

                 $db_conn = mysql_connect('localhost', 'root', '') or die('error');
                    mysql_select_db('db_scrap', $db_conn) or die(mysql_error());

                    $sql = "INSERT INTO scrap_data(url, imges) VALUES ('".$item_a."', '".$item_img."')";

                    mysql_query($sql) or die(mysql_error()); 
                 }

我的问题是,如何将所有获取值插入到表的特定列中。像 标签插入到 url 列和 标签值插入到图像列?

【问题讨论】:

  • 您应该通过嵌入纯文本文件来替换图像。

标签: php html mysql web-scraping


【解决方案1】:

你总是在你的 foreach 中覆盖你的 $item_a 和 $item_img。

你需要类似的东西

$items_a = array();
foreach($items->find('a') as $anchor) {
    array_push($items_a, $anchor->href)
}

图像也是如此。最后,简单地对数组进行内爆

$item_a = implode(';', $items_a);

你就完成了。

        include './simple_html_dom.php';       //Inlcude HTML DOM
        $html = file_get_html('http://tacticalwalls.com/shop/');  //Scrapping site/url
          //**ul[class=products] here is specific DIV values** 
        foreach ($html->find('ul[class=products]') as $items) {
            $items_a = array();
            foreach ($items->find('a') as $anchor) {          
                array_push($items_a, $anchor->href);
            }
            $items_img = array();
            foreach ($items->find('img') as $img){
                array_push($items_img, $img->src);
            }
            $item_a = implode(';', $items_a);
            $item_img = implode(';', $items_img);
            $db_conn = mysql_connect('localhost', 'root', '') or die('error');
            mysql_select_db('db_scrap', $db_conn) or die(mysql_error());

            $sql = "INSERT INTO scrap_data(url, imges) VALUES ('".$item_a."', '".$item_img."')";

            mysql_query($sql) or die(mysql_error()); 
        }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 2013-04-05
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多