2017-09-11 8 views
0

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); 

답변

0

당신은 당신은 XPath에의 패턴을 볼 수 있습니다

$xml = new SimpleXMLElement($string); 
$tags = $xml->xpath("//h1 | //h2 | //h3 | //h4"); 
$data = []; 
foreach ($tags as $tag) { 
    $elementData['name'] = $tag->getName(); 
    $elementData['content'] = (string)$tag; 
    $data[] = $elementData; 
} 

print_r($data); 

당신이 시도 할 수있는 짧고 훨씬 더 읽을 버전 ...이, 그것은 SimpleXML을하고 XPath를 사용하고 싶어하는 경우 - 그것은 필요한 모든 요소를 ​​결합합니다. //을 사용하면 원하는 레벨을 찾은 다음 찾으려는 요소의 이름을 찾을 수 있습니다. 이들은 '또는'연산자 인 |을 사용하여 결합됩니다. 동일한 유형의 표현식을 사용하여 필요한 태그 풀 세트를 쉽게 확장 할 수 있습니다.

프로그램은 찾은 요소를 반복하고 한 번에 각 요소의 배열을 만듭니다. 이름과 내용을 가져 와서 $ 데이터 배열에 추가합니다.

업데이트 : 파일 형식이 XML 인 경우 DOMDocument 및 loadHTML을 사용해야 할 수 있습니다. 단지 약간의 차이가 있지만 더 많은 오류의 tollerant입니다 ...

$string = file_get_contents("links.html"); 
$xml = new DOMDocument(); 
libxml_use_internal_errors(); 
$xml->loadHTML($string); 
$xp = new DOMXPath($xml); 
$tags = $xp->query("//h1 | //h2 | //h3 | //h4"); 
$data = []; 
foreach ($tags as $tag) { 
    $elementData['name'] = $tag->tagName; 
    $elementData['content'] = $tag->nodeValue; 
    $data[] = $elementData; 
} 

print_r($data); 
+0

그리고 어떻게 그 문자열에 html 파일을 읽는가 ?? –

+0

같은 방법으로 이미 - $ string = file_get_contents ('test.php'); ' –

+0

이 작업을 수행하려고하는데이 오류가 표시됩니다. "문자열을 XML로 구문 분석 할 수 없습니다." –