PHP simple_html_dom从url中提取数据

时间:2014-11-01 09:46:33

标签: php html web-scraping simple-html-dom

我的代码有什么问题?为什么它不起作用?

这是我尝试使用的代码:

function extract_data($url){

    // Create DOM from URL
    $html = file_get_html($url);

    // initialize empty array to store the data array from each row
    $theData = array();

    // loop over rows
    foreach($html->find('p.ch_title') as $row) {

        // initialize array to store the cell data from each row
        $rowData = array();
        foreach($row->find('p.ch_spec') as $cell) {

            // push the cell's text to the array
            $rowData[] = $cell->innertext;
        }

        // push the row's data array to the 'big' array
        $theData[] = $rowData;
    }

    return $theData;

}

这是来自网址的html数据;

<div class="holder-specificatii">
       <div class="box-specificatie">
          <div class="ch_group">Dimensiuni</div>
          <p class="ch_title">Latime (mm):</p>
          <p class="ch_spec">195</p>
          <p class="ch_title">Inaltime:</p>
          <p class="ch_spec">65</p>
          <p class="ch_title">Diametru (inch):</p>
          <p class="ch_spec">15</p>
          <div class="clear"></div>
       </div>
       <div class="box-specificatie">
          <div class="ch_group">Caracteristici tehnice</div>
          <p class="ch_title">Anotimp:</p>
          <p class="ch_spec">Iarna</p>
          <p class="ch_title">Indice sarcina:</p>
          <p class="ch_spec">91</p>
          <p class="ch_title">Indice viteza:</p>
          <p class="ch_spec">T</p>
          <p class="ch_title">Economie de carburant:</p>
          <p class="ch_spec">C</p>
          <p class="ch_title">Franare pe suprafete umede:</p>
          <p class="ch_spec">C</p>
          <p class="ch_title">Tip vehicul:</p>
          <p class="ch_spec">Turism</p>
          <p class="ch_title">DOT:</p>
          <p class="ch_spec">2014</p>
          <p class="ch_title">Nivel de zgomot (dB):</p>
          <p class="ch_spec">72dB</p>
          <div class="clear"></div>
       </div>
    </div>

问题是返回空数组的函数。

2 个答案:

答案 0 :(得分:1)

您指向未定义的对象,您应该使用$html代替:

function extract_data($url){

    $html = file_get_html($url);
    $theData = array();
    // loop over rows
    foreach($html->find('div.box-specificatie') as $k => $row) { // loop each container
        $temp = array();
        // $main_title = $row->find('div.ch_group', 0)->innertext;
        foreach($row->find('p.ch_title') as $title) { // each title
            $spec = $title->next_sibling()->innertext(); // pair up with spec
            $temp[] = array('title' => $title->innertext, 'spec' => $spec);
        }
        $theData[$k] = $temp; // push inside
        // $theData[$main_title] = $temp; // optionally you can use a main title

    }

    return $theData;
}

echo '<pre>';
print_r(extract_data($url));

答案 1 :(得分:0)

在你正在做的第一个foreach中,你使用从file_get_html收到的html,但在嵌套的foreach中你使用了返回的$ row,并且它没有p.ch_spec因为isn&#39; ta p.ch_title的孩子。