簡體   English   中英

使用簡單HTML Dom庫從網頁獲取值

[英]Getting values from webpage using Simple HTML Dom library

我正在嘗試從網頁中的表中獲取值,為此,我正在使用簡單HTML Dom庫。 這是我的代碼的樣子:

include('simple_html_dom.php');

$html = file_get_html('http://www.lvbp.com/posicion.html');

$arr = array();
foreach ($html->find('tr') as $e) {
    array_push($arr, $e->innertext);
}

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

for ($i = 2; $i < count($arr); $i++) {
    str_replace("", "-", $arr[$i]);
    print_r($arr[$i]);
}

print_r($arr)時,我將其作為輸出:

Array
(
    [0] =>       EQUIPOS      J      G      P      Vent    
    [1] => 
    [2] =>       Navegantes      11      8      3      0    
    [3] =>       Tigres      11      8      3      0    
    [4] =>       Caribes      11      6      5      2    
    [5] =>       Leones      11      6      5      2    
    [6] =>       Aguilas      11      5      6      3    
    [7] =>       Tiburones      10      4      6      3.5    
    [8] =>       Cardenales      10      3      7      4.5    
    [9] =>       Bravos      11      3      8      5    
)

但是從這里開始,我需要分別獲取每個數組位置的“ Navegantes”,“ 11”,“ 8”等含義。 為此,我最后的代碼:

for ($i = 2; $i < count($arr); $i++) {
    str_replace("", "-", $arr[$i]);
    print_r($arr[$i]);
}

但這不起作用,因為我得到以下結果:

Navegantes 11 8 3 0 Tigres 11 8 3 0 Caribes 11 6 5 2 Leones 11 6 5 2 Aguilas 11 5 6 3 Tiburones 10 4 6 3.5 Cardenales 10 3 7 4.5 Bravos 11 3 8 5 

我想念的是什么? 有什么幫助嗎?

UPDATE

根據建議,這是我的代碼的樣子:

include('simple_html_dom.php');
$html = file_get_html('http://www.lvbp.com/posicion.html');

$arr = array();
foreach ($html->find('tr') as $e) {
    $narr = array();
    foreach ($e->find('td') as $vp) {
        array_push($narr, $vp->plaintext);
    }
    $arr[] = array($narr);
}

嘗試這個 :

$arr = array();
foreach ($html->find('tr') as $e) {
 $narr=array();
 foreach($e->find('td') as $vp){
  array_push($narr,$vp->plaintext);
 }
 $arr[]=array($narr);
}

代替 :

foreach ($html->find('tr') as $e) {
    array_push($arr, $e->innertext);
}

並刪除代碼:

for ($i = 2; $i < count($arr); $i++) {
    str_replace("", "-", $arr[$i]);
    print_r($arr[$i]);
}

您將獲得一個數組,其中鍵作為tr標記,其值作為tr的每個td

這是一個方法:

// includes Simple HTML DOM Parser
include "simple_html_dom.php";

$url = "http://www.lvbp.com/posicion.html";

//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load_file($url);

// parse rows
foreach ($html->find('tr') as $i => $row) {

    // Skip the second empty row
    if ($i == 1)
        continue;

    // parse and print cells
    foreach ($row->find('td') as $j => $col) {
        echo $col->plaintext;
        echo "|";
    }
    echo "<hr>";
}


// Clear DOM object (needed essentially when using many)
$html->clear(); 
unset($html);

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM