PHP에서 HTML 구문 분석

Olorunfemi Akinlua 2023년1월30일
  1. DomDocument()를 사용하여 PHP에서 HTML 구문 분석
  2. simplehtmldom을 사용하여 PHP에서 HTML 구문 분석
  3. DiDOM을 사용하여 PHP에서 HTML 구문 분석
PHP에서 HTML 구문 분석

HTML을 구문 분석하면 콘텐츠 또는 마크업을 문자열로 변환할 수 있으므로 동적 HTML 파일을 더 쉽게 분석하거나 생성할 수 있습니다. 더 자세하게는 원시 HTML 코드를 가져와서 읽고 단락에서 제목까지 DOM 트리 개체 구조를 생성하고 중요하거나 필요한 정보를 추출할 수 있도록 합니다.

우리는 내장 라이브러리를 사용하여 HTML 파일을 구문 분석하고 때로는 PHP에서 웹 스크래핑 또는 콘텐츠 분석을 위해 타사 라이브러리를 구문 분석합니다. 방법에 따라 HTML 문서 본문을 문자열로 변환하여 각 HTML 태그를 추출하는 것이 목표입니다.

이 기사에서는 내장 클래스 DomDocument()와 두 개의 타사 라이브러리 simplehtmldomDiDOM에 대해 설명합니다.

DomDocument()를 사용하여 PHP에서 HTML 구문 분석

로컬 HTML 파일이든 온라인 웹 페이지이든 DOMDocument()DOMXpath() 클래스는 HTML 파일을 구문 분석하고 해당 요소를 문자열로 저장하거나 이 예의 경우 배열로 저장하는 데 도움이 됩니다.

함수를 사용하여 이 HTML 파일을 구문 분석하고 제목, 하위 제목 및 단락을 반환해 보겠습니다.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h2 class="main">Welcome to the Abode of PHP</h2>
        <p class="special">
            PHP has been the saving grace of the internet from its inception, it
            runs over 70% of website on the internet
        </p>
        <h3>Understanding PHP</h3>
        <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus
            eos cupiditate earum et optio culpa, eligendi facilis laborum
            dolore.
        </p>
        <h3>Using PHP</h3>
        <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus
            eos cupiditate earum et optio culpa, eligendi facilis laborum
            dolore.
        </p>
        <h3>Install PHP</h3>
        <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus
            eos cupiditate earum et optio culpa, eligendi facilis laborum
            dolore.
        </p>
        <h3>Configure PHP</h3>
        <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus
            eos cupiditate earum et optio culpa, eligendi facilis laborum
            dolore.
        </p>

        <h2 class="main">Welcome to the Abode of JS</h2>
        <p class="special">
            PHP has been the saving grace of the internet from its inception, it
            runs over 70% of website on the internet
        </p>
        <h3>Understanding JS</h3>
        <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus
            eos cupiditate earum et optio culpa, eligendi facilis laborum
            dolore.
        </p>
    </body>
</html>

PHP 코드:

<?php

$html = 'index.html';

function getRootElement($element, $html)
{
    $dom = new DomDocument();

    $html = file_get_contents($html);

    $dom->loadHTML($html);

    $dom->preserveWhiteSpace = false;

    $content = $dom->getElementsByTagName($element);

    foreach ($content as $each) {
        echo $each->nodeValue;
        echo "\n";
    }
}

echo "The H2 contents are:\n";
getRootElement("h2", $html);
echo "\n";

echo "The H3 contents are:\n";
getRootElement("h3", $html);
echo "\n";

echo "The Paragraph contents include\n";
getRootElement("p", $html);
echo "\n";

코드 조각의 출력은 다음과 같습니다.

The H2 contents are:
Welcome to the Abode of PHP
Welcome to the Abode of JS

The H3 contents are:
Understanding PHP
Using PHP
Install PHP
Configure PHP
Understanding JS

The Paragraph contents include

PHP has been the saving grace of the internet from its inception, it
runs over 70% of the website on the internet

...

simplehtmldom을 사용하여 PHP에서 HTML 구문 분석

CSS 스타일 선택기와 같은 추가 기능을 위해 간단하고 빠른 PHP 파서인 Simple HTML DOM Parser라는 타사 라이브러리를 사용할 수 있습니다. 다운로드하여 단일 PHP 파일을 포함하거나 요구할 수 있습니다.

이 프로세스를 통해 원하는 모든 요소를 ​​쉽게 구문 분석할 수 있습니다. 이전 섹션과 동일한 코드 조각을 사용하여 str_get_html()이라는 함수를 사용하여 HTML을 구문 분석합니다. 이 함수는 HTML을 처리하고 find() 메서드를 사용하여 특정 HTML 요소 또는 태그를 찾습니다.

특별한 class가 있는 요소를 찾으려면 각 find 요소에 적용할 class 선택기가 필요합니다. 또한 실제 텍스트를 찾으려면 요소에서 innertext 선택기를 사용해야 하며 이를 배열에 저장합니다.

마지막 섹션과 동일한 HTML 파일을 사용하여 simplehtmldom을 사용하여 구문 분석해 보겠습니다.

<?php

require_once('simple_html_dom.php');

function getByClass($element, $class)
{
    $content= [];

    $html = 'index.html';

    $html_string = file_get_contents($html);

    $html = str_get_html($html_string);

    foreach ($html->find($element) as $element) {
        if ($element->class === $class) {
            array_push($heading, $element->innertext);
        }
    }

    print_r($content);
}

getByClass("h2", "main");
getByClass("p", "special");

코드 조각의 출력은 다음과 같습니다.

Array
(
    [0] => Welcome to the Abode of PHP
    [1] => Welcome to the Abode of JS
)
Array
(
    [0] =>               PHP has been the saving grace of the internet from its inception, it              runs over 70% of the website on the internet
    [1] =>               PHP has been the saving grace of the internet from its inception, it              runs over 70% of the website on the internet
)

DiDOM을 사용하여 PHP에서 HTML 구문 분석

이 타사 PHP 라이브러리의 경우 Composer라는 PHP 종속성 관리자를 사용해야 합니다. 이를 통해 모든 PHP 라이브러리와 종속성을 관리할 수 있습니다. DiDOM 라이브러리는 GitHub를 통해 사용할 수 있으며 다른 라이브러리보다 더 빠른 속도와 메모리 관리를 제공합니다.

없으시다면 Composer here를 설치하시면 됩니다. 그러나 다음 명령은 DiDOM 라이브러리가 있는 경우 프로젝트에 추가합니다.

composer require imangazaliev/didom

그런 다음 find() 메소드를 사용하여 simplehtmldom과 유사한 구조의 아래 코드를 사용할 수 있습니다. HTML 요소 컨텍스트를 코드에서 사용할 수 있는 문자열로 변환하는 text()가 있습니다.

has() 함수를 사용하면 HTML 문자열 내에 요소 또는 클래스가 있는지 확인하고 부울 값을 반환합니다.

<?php

use DiDom\Document;

require_once('vendor/autoload.php');

$html = 'index.html';

$document = new Document('index.html', true);

echo "H3 Element\n";

if ($document->has('h3')) {
    $elements = $document->find('h3');
    foreach ($elements as $element) {
        echo $element->text();
        echo "\n";
    }
}

echo "\nElement with the Class 'main'\n";

if ($document->has('.main')) {
    $elements = $document->find('.main');
    foreach ($elements as $element) {
        echo $element->text();
        echo "\n";
    }
}

코드 조각의 출력은 다음과 같습니다.

H3 Element
Understanding PHP
Using PHP
Install PHP
Configure PHP
Understanding JS

Element with the Class 'main'
Welcome to the Abode of PHP
Welcome to the Abode of JS
Olorunfemi Akinlua avatar Olorunfemi Akinlua avatar

Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.

LinkedIn

관련 문장 - PHP HTML