HTML 페이지를 구문 분석하고 일부 태그에 액세스하려고합니다. 나는 모든 태그를 파싱하고 결과를 태그 수준에 따른 들여 쓰기 형태로 표시하고 있습니다. 헤더 태그 h1, h2, h3 등. 이제 결과 데이터 (들여 쓰기 된 목차)를 태그 이름과 함께 배열에 저장하려고합니다. 친절하게 내 문제를 해결하도록 도와주세요.PHP html 구문 분석, 구문 분석 된 요소를 배열에 저장하려고합니다.
여기 내 PHP 코드입니다 ... html dom 파서를 사용하고 있습니다.
include ("simple_html_dom.php");
session_start();
error_reporting(0);
$string = file_get_contents('test.php');
$tags = array(0 => '<h1', 1 => '<h2', 2 => '<h3', 3 => '<h4', 4 => '<h5', 5 => '<h6');
function parser($html, $needles = array()){
$positions = array();
foreach ($needles as $needle){
$lastPos = 0;
while (($lastPos = strpos($html, $needle, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
unset($needles[0]);
if(count($positions) > 0){
break;
}
}
if(count($positions) > 0){
for ($i = 0; $i < count($positions); $i++) {
?>
<div class="<?php echo $i; ?>" style="padding-left: 20px; font-size: 14px;">
<?php
if($i < count($positions)-1){
$temp = explode('</', substr($html, $positions[$i]+4));
$pos = strpos($temp[0], '>');
echo substr($temp[0], $pos);
parser(substr($html, $positions[$i]+4, $positions[$i+1]-$positions[$i]-4), $needles);
} else {
$temp = explode('</', substr($html, $positions[$i]+4));
$pos = strpos($temp[0], '>');
echo substr($temp[0], $pos+1);
parser(substr($html, $positions[$i]+4), $needles);
}
?>
</div>
<?php
}
} else {
// not found any position of a tag
}
}
parser($string, $tags);
그리고 어떻게 그 문자열에 html 파일을 읽는가 ?? –
같은 방법으로 이미 - $ string = file_get_contents ('test.php'); ' –
이 작업을 수행하려고하는데이 오류가 표시됩니다. "문자열을 XML로 구문 분석 할 수 없습니다." –