1 回答

TA貢獻1806條經驗 獲得超5個贊
我看到的幾個問題:
$tables->item(1)->getElementsByTagName('tr');
將始終為您提供頁面中的第二個表格,該表格將是右側個人統計數據塊中的表格由于
$cols[2]
不是簡單類型的對象,您將收到警告而不是內容。用于echo $cols[2]->textContent
輸出內部文本。
我建議加載所有表,然后根據結果表中不同的表標題進行檢查(如果您正在解析結果表)。然后提取適當的列。
示例代碼:
下面的代碼僅顯示如何檢查表中的示例標題“Result”,然后輸出結果列。請根據您的預期目的進行調整。
<?php
$table = file_get_contents('https://en.wikipedia.org/wiki/Sugar_Ray_Robinson');
$dom = new DOMDocument;
$dom->loadHTML($table);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
foreach ($tables as $singleTable) {
try {
$rows = $singleTable->getElementsByTagName('tr');
// check if we are parsing the right table:
$row1= $rows[0]->getElementsByTagName('th');
$isResultTable= FALSE;
foreach ($row1 as $th) {
if (trim($th->textContent) === 'Result') {
$isResultTable = TRUE;
}
}
if (!$isResultTable) continue;
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
echo $cols[2]->textContent;
}
} catch (Exception $ex) {
print_r($ex);
}
}
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報