« 2019年10月 | メイン | 2019年12月 »

2019年11月07日

phpでhtmlのパース

ページ全体simplexml_load_stringするとタグが壊れて動かない事も多いので必要部分を抜き出したうえでやってます。

$html = file_get_contents("html.txt");

libxml_use_internal_errors(true);
$domDocument = new DOMDocument();
$domDocument->encoding = "UTF-8";
$domDocument->loadHTML($html);

$mytag = "";
foreach ($domDocument->getElementsByTagName('table') as $node) {
	$tag = $domDocument->saveHtml($node);
	if(strpos($tag,'forecastDetail-hour_table') !== false ){
		$mytag = $tag;
		break;
	}
}

$domDocument->loadHTML( mb_convert_encoding($mytag, 'HTML-ENTITIES', 'UTF-8') );

$domDocument->encoding = "UTF-8";
$xmlString = $domDocument->saveXML();


$xmlObject = simplexml_load_string($xmlString);
$json = json_encode($xmlObject);
$array = array();
$array = json_decode($json,TRUE);

print_r($array);//["body"]["tr"]["td"][0]["span"][1];

exit;

投稿者 muuming : 14:46