[英]convert HTML table to PHP Array using JSDOM
我想將此表 HTML 轉換為 PHP 數組
到目前為止我已經嘗試過:
<?php
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$html = curl('https://www.ortax.org/ortax/?mod=kursbi');
$data = array();
foreach((@DOMDocument::loadHTML($html))->getElementsByTagName("td") as $tag){
$data[trim($tag->textContent)]=trim($tag->nextSibling->nextSibling->textContent);
}
echo '<pre>';
print_r($data);
echo '</pre>';
?>
我得到的結果:這個錯誤:
Notice: Trying to get property 'textContent' of non-object in D:\XAMPP\htdocs\curl\curl.php on line 16
這個數組:
Array
(
[] => Error Etax-40001
[Planning SPT Tahunan: PPh 22, 23, 25 Lebih Bayar] =>
[Kewajiban NIK Untuk Faktur Pajak] =>
[Billing DJBC] =>
[Bagaimana Cara Mengatasi E-Bupot PPh 23/26 Yang Error?] =>
[Error Etax-40001] =>
[Dolar Australia [ AUD ]] => 1
[1] => 0.62
[10850.85] => 10741.47
[10741.47] => 10796.16
[10796.16] =>
)
我想要的結果是我只想要數字數組中的表格內容並擺脫上面的錯誤:
Array
(
[0] => Array
(
[0] => Dolar Australia [ AUD ]
[1] => 1
[2] => 10850.85
[3] => 10741.47
[4] => 10796.16
)
)
這是 hacky 解決方案,但這應該有效。
從您得到的結果中,您似乎選擇了頁面中存在的所有<td>
,您將獲得不需要的數據。 如果可能的話,如果您只從您需要的特定表中獲取 select 會更好。
$table = @DOMDocument::loadHTML($html)->getElementsByTagName("table")->item(1);
$i=-1;
foreach($table->getElementsByTagName('tr') as $row){
$j = 0;
foreach($row->getElementsByTagName('td') as $tag){
//echo $tag->textContent."<br>";
$data[$i][$j] = $tag->textContent;
$j++;
}
$i++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.