Parsing html file in php

Parse HTML in PHP

Parse HTML in PHP

  1. Use DomDocument() to Parse HTML in PHP
  2. Use simplehtmldom to Parse HTML in PHP
  3. Use DiDOM to Parse HTML in PHP

Parsing HTML allows us to convert its content or markup to string, making it easier to analyze or create a dynamic HTML file. In more detail, it takes the raw HTML code, reads it, generates a DOM tree object structure from the paragraphs to the headings, and allows us to extract the important or needed information.

We parse HTML files using built-in libraries and sometimes third-party libraries for web scraping or content analysis in PHP. Depending on the method, the goal is to convert the HTML document body into a string to extract each HTML tag.

This article will discuss the built-in class, DomDocument() , and two third-party libraries, simplehtmldom and DiDOM .

Use DomDocument() to Parse HTML in PHP

Whether a local HTML file or an online webpage, the DOMDocument() and DOMXpath() classes help with parsing an HTML file and storing its element as strings or, in the case of our example, an array.

Let’s parse this HTML file using the functions and return the headings, sub-headings, and paragraphs.

 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>Documenttitle>  head>  body>  h2 class="main">Welcome to the Abode of PHPh2>  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 PHPh3>  p>  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus  eos cupiditate earum et optio culpa, eligendi facilis laborum  dolore.  p>  h3>Using PHPh3>  p>  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus  eos cupiditate earum et optio culpa, eligendi facilis laborum  dolore.  p>  h3>Install PHPh3>  p>  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eum minus  eos cupiditate earum et optio culpa, eligendi facilis laborum  dolore.  p>  h3>Configure PHPh3>  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 JSh2>  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 JSh3>  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  $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 output of the code snippet is:

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  . 

Use simplehtmldom to Parse HTML in PHP

For additional functionalities such as CSS style selectors, you can use a third-party library called Simple HTML DOM Parser, which is a simple and fast PHP parser. You can download it and include or require the single PHP file.

With this process, you can easily parse through all the elements you want. Using the same code snippet as in the previous section, we will parse the HTML using a function called str_get_html() , which processes the HTML and uses the find() method to look for a specific HTML element or tag.

To find an element with a special class , we need the class selector to apply to each find element. Also, to find the actual text, we need to use the innertext selector on the element, which we then store in the array.

Using the same HTML file as the last section, let’s parse through it using the 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"); 

The output of the code snippet is:

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 ) 

Use DiDOM to Parse HTML in PHP

For this third-party PHP library, we have to use a PHP dependency manager called Composer, which allows us to manage all our PHP libraries and dependencies. The DiDOM library is available via GitHub and provides more speed and memory management than other libraries.

If you don’t have it, you can install Composer here. However, the following command adds the DiDOM library to your project if you have it.

composer require imangazaliev/didom 

After that, you can use the code below, which has a similar structure to simplehtmldom with the find() method. There is a text() , which converts the HTML element contexts to strings we can use in our code.

The has() function allows you to check if you have an element or a class within your HTML string and returns a Boolean value.

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

The output of the code snippet is:

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 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.

Related Article — PHP HTML

Источник

Парсинг и обработка веб-страницы на PHP: выбираем лучшую библиотеку

Обложка: Парсинг и обработка веб-страницы на PHP: выбираем лучшую библиотеку

Задача спарсить и обработать необходимую информацию со стороннего сайта встает перед веб-разработчиком довольно часто и по самым разнообразным причинам: таким образом можно заполнять свой проект контентом, динамически подгружать какую-то информацию и так далее.

В таких случаях перед программистом встает вопрос: какую из десятков библиотек выбрать? В этой статье мы постарались рассмотреть самые популярные варианты и выбрать из них лучший.

Регулярные выражения

Даже не смотря на то, что «регулярки» — это первое, что приходит на ум, использовать их для настоящих проектов не стоит.

Да, с простыми задачами регулярные выражения справляются лучше всех, но его использование значительно затрудняется, когда нужно спарсить большой и сложный кусок HTML-кода, который, к тому же, не всегда соответствует какому-то определенному шаблону и вообще может содержать синтаксические ошибки.

Вместо «допиливания» своего регулярного выражения при каждом малейшем изменении кода рекомендуем использовать инструменты ниже — это и проще, и удобнее, и надежнее.

XPath и DOM

DOM и XPath не являются библиотеками в привычном смысле этого слова, это стандартные модули, которые встроены в PHP начиная с пятой версии. Именно отсутствие необходимости использовать сторонние решения делает их одними из лучших инструментов для парсинга HTML страниц.

На первый взгляд может показаться, что низкий порог входа — это не о них, некоторые места и вправду являются весьма сложными. Но это только на первый взгляд: стоит только немного разобраться с синтаксисом и базовыми принципами, как XPath тут же станет для вас инструментом для парсинга номер один.

Вот, например, код с использованием DOM и XPath, который ищет в разметке все теги и модифицирует их атрибуты src :

$dom = new DOMDocument; $dom->loadHTML($html); $images = $dom->getElementsByTagName('img'); foreach ($images as $image) < $image->setAttribute('src', 'http://example.com/' . $image->getAttribute('src')); > $html = $dom->saveHTML();

Тем не менее, данный вариант не лишен минусов — для парсинга используется движок, в первую очередь предназначенный для работы с XML, а XML и HTML хоть и являются очень похожими языками, но всё же различаются. Из этого вытекают специфические требования к разметке: например, все HTML теги должны быть закрыты.

Simple HTML DOM

Simple HTML DOM — PHP-библиотека, позволяющая парсить HTML-код с помощью удобных jQuery-подобных селекторов.

Она лишена главного недостатка XPath — библиотека умеет работать даже с невалидным HTML-кодом, что значительно упрощает работу. Вы также забудете о проблемах с кодировкой: все преобразования выполняются автоматически.

Как и JQuery, Simple HTML DOM умеет искать и фильтровать вложенные элементы, обращаться к их атрибутам и даже выбирать отдельные логические элементы кода, например, комментарии.

В этом примере сначала подгружается, а потом модифицируется заранее заготовленный HTML-код: во второй строке происходит добавление атрибута class со значением bar первом попавшемуся элементу div , а в следующей строке мы заменяем текст элемента с id=”world” на foo .

$html = str_get_html('
Hello
World
'); $html->find('div', 1)->class = 'bar'; $html->find('div[id=world]', 0)->innertext = 'foo'; echo $html;

Несмотря на не самую высокую производительность, по сравнению с другими вариантами, Simple HTML DOM имеет самое большое русскоязычное комьюнити и наибольшую распространенность в рунете — для новичков это делает написание кода с её использованием значительно проще.

phpQuery

Как и Simple HTML DOM, phpQuery является PHP вариантом JQuery, но на этот раз более похожим на своего «старшего javascript-брата».

Портировано почти всё, что есть в JS-фреймворке: поддержка селекторов, атрибутов, манипуляций, обхода, плагинов, событий (в том числе имитации кликов и т.д.) и даже AJAX. Использовать можно как через PHP, так и через командную строку в виде отдельного приложения.

Более того, согласно нашим бенчмаркам, phpQuery оказался в 8 (!) раз быстрее Simple HTML DOM.

Вот небольшой пример на phpQuery, в котором происходит обработка заранее выбранных элементов списка ( li ):

foreach(pq('li') as $li) < // Можно вывести различные данные обычным текстом $tagName = $li->tagName; $childNodes = $li->childNodes; // А можно добавить обертку phpQuery (аналог $() в JQuery) и, например, добавить к элементу какой-то класс pq($li)->addClass('my-second-new-class'); >

Подробную документацию и больше примеров найдете на официальной странице в Google Code.

htmlSQL

htmlSQL — экспериментальная PHP библиотека, позволяющая манипулировать HTML-разметкой посредством SQL-подобных запросов.

Простейший пример, извлекающий атрибуты href и title всех ссылок (элементы a ) с классом list :

SELECT href,title FROM a WHERE $class == "list"

Как и с обычными mysql_ функциями, воспользовавшись методами fetch_array() или fetch_objects(), мы можем получить результат выполнения данного запроса в виде привычного ассоциативного массива или объекта.

Стоит также упомянуть о высоком быстродействии htmlSQL: часто она справляется в несколько раз быстрее phpQuery или того же Simple HTML DOM.

Тем не менее, для сложных задач вам может не хватить функциональности, а разработка библиотеки давно прекращена. Но даже несмотря на это, она всё ещё представляет интерес для веб-разработчиков: в ряде случаев значительно удобнее использовать язык SQL вместо CSS-селекторов. Особенно когда вы не знаете, что такое CSS-селекторы 😉

Вывод

В своем мини-исследовании мы пришли к выводу, что в большинстве случаев для парсинга лучше использовать библиотеку phpQuery: она быстрая, функциональная и современная.

С другой стороны, для совсем простых задач логично было бы использовать стандартные модули PHP, такие как XPath, DOM или, на крайний случай, регулярные выражения.

Что-то ещё?

Для PHP существуют ещё десятки разнообразных библиотек и инструментов для парсинга, но в этой статье мы рассмотрели только самые интересные, функциональные и производительные.

Подробнее о других способах парсинга средствами PHP можно прочитать в соответствующей теме на StackOverflow.

Если вы не используете PHP, то можете ознакомится с кратким списком похожих инструментов для других языков программирования:

.NET: Html Agility Pack;

Источник

Читайте также:  Javascript manual на русском
Оцените статью