1 回答

TA貢獻1806條經(jīng)驗 獲得超5個贊
我看到的幾個問題:
$tables->item(1)->getElementsByTagName('tr');
將始終為您提供頁面中的第二個表格,該表格將是右側(cè)個人統(tǒng)計數(shù)據(jù)塊中的表格由于
$cols[2]
不是簡單類型的對象,您將收到警告而不是內(nèi)容。用于echo $cols[2]->textContent
輸出內(nèi)部文本。
我建議加載所有表,然后根據(jù)結(jié)果表中不同的表標題進行檢查(如果您正在解析結(jié)果表)。然后提取適當?shù)牧小?/p>
示例代碼:
下面的代碼僅顯示如何檢查表中的示例標題“Result”,然后輸出結(jié)果列。請根據(jù)您的預期目的進行調(diào)整。
<?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 關(guān)注
- 175 瀏覽
添加回答
舉報