Convert Figma logo to code with AI

Masterminds logohtml5-php

An HTML5 parser and serializer for PHP.

1,614
115
1,614
36

Top Related Projects

Eases DOM navigation for HTML and XML documents

23,156

Guzzle, an extensible PHP HTTP client

Standards compliant HTML filter written in PHP

Quick Overview

HTML5-PHP is a standards-compliant HTML5 parser and serializer for PHP. It provides a robust set of tools for working with HTML5 documents, including parsing, manipulating, and serializing HTML content. This library aims to be fully compliant with the HTML5 specification while offering an intuitive API for PHP developers.

Pros

  • Fully compliant with the HTML5 specification
  • Supports both parsing and serializing HTML documents
  • Provides a comprehensive set of DOM manipulation tools
  • Well-documented and actively maintained

Cons

  • May have a steeper learning curve compared to simpler HTML parsing libraries
  • Performance might be slower for very large HTML documents
  • Requires PHP 5.3.0 or higher, which may be a limitation for some legacy projects
  • Limited support for XML-specific features

Code Examples

  1. Parsing an HTML document:
<?php
use Masterminds\HTML5;

$html = new HTML5();
$dom = $html->loadHTML('<html><body><h1>Hello, World!</h1></body></html>');
  1. Manipulating the DOM:
<?php
$h1 = $dom->getElementsByTagName('h1')->item(0);
$h1->textContent = 'Updated Heading';
$body = $dom->getElementsByTagName('body')->item(0);
$p = $dom->createElement('p', 'New paragraph');
$body->appendChild($p);
  1. Serializing the modified DOM:
<?php
$output = $html->saveHTML($dom);
echo $output;

Getting Started

To use HTML5-PHP in your project, follow these steps:

  1. Install the library using Composer:

    composer require masterminds/html5
    
  2. Include the Composer autoloader in your PHP script:

    <?php
    require 'vendor/autoload.php';
    
  3. Use the library in your code:

    <?php
    use Masterminds\HTML5;
    
    $html = new HTML5();
    $dom = $html->loadHTML('<html><body><h1>Hello, HTML5-PHP!</h1></body></html>');
    // Manipulate the DOM as needed
    $output = $html->saveHTML($dom);
    echo $output;
    

Competitor Comparisons

Eases DOM navigation for HTML and XML documents

Pros of dom-crawler

  • Part of the larger Symfony ecosystem, offering better integration with other Symfony components
  • More actively maintained with frequent updates and bug fixes
  • Provides a fluent interface for traversing and manipulating DOM elements

Cons of dom-crawler

  • Focused primarily on DOM manipulation, lacking full HTML5 parsing capabilities
  • May have a steeper learning curve for developers not familiar with Symfony components
  • Less suitable for standalone use outside of Symfony projects

Code Comparison

html5-php:

$html = file_get_contents('example.html');
$dom = new \Masterminds\HTML5();
$doc = $dom->loadHTML($html);
$elements = $doc->getElementsByTagName('div');

dom-crawler:

use Symfony\Component\DomCrawler\Crawler;

$html = file_get_contents('example.html');
$crawler = new Crawler($html);
$elements = $crawler->filter('div');

Summary

While html5-php offers more comprehensive HTML5 parsing capabilities, dom-crawler excels in DOM manipulation within the Symfony ecosystem. html5-php may be better suited for standalone projects requiring full HTML5 support, while dom-crawler is ideal for Symfony-based applications or projects needing advanced DOM traversal and manipulation features.

23,156

Guzzle, an extensible PHP HTTP client

Pros of Guzzle

  • Comprehensive HTTP client library with support for various request types and methods
  • Extensive documentation and active community support
  • Built-in support for asynchronous requests and parallel processing

Cons of Guzzle

  • Larger footprint and potentially more complex for simple HTTP requests
  • Not specifically designed for HTML parsing or manipulation

Code Comparison

html5-php (HTML parsing):

$html = file_get_contents('example.html');
$dom = new HTML5DOMDocument();
$dom->loadHTML($html);
$elements = $dom->getElementsByTagName('div');

Guzzle (HTTP request):

$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'https://example.com');
$body = $response->getBody();
$html = (string) $body;

Summary

html5-php is focused on HTML5 parsing and manipulation, while Guzzle is a comprehensive HTTP client library. html5-php is better suited for working with HTML content directly, whereas Guzzle excels in making HTTP requests and handling responses. The choice between the two depends on the specific requirements of your project, whether it's primarily HTML parsing or HTTP communication.

Standards compliant HTML filter written in PHP

Pros of HTMLPurifier

  • More focused on security and sanitization of HTML input
  • Extensive configuration options for fine-tuning output
  • Well-established project with a long history and large user base

Cons of HTMLPurifier

  • Slower performance compared to html5-php
  • Less support for modern HTML5 features
  • More complex setup and usage for basic parsing tasks

Code Comparison

HTMLPurifier:

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

html5-php:

$html = new HTML5();
$dom = $html->loadHTML($input);
$output = $html->saveHTML($dom);

HTMLPurifier focuses on sanitizing and cleaning HTML input, making it ideal for user-generated content. It offers extensive configuration options but may be overkill for simple parsing tasks. html5-php, on the other hand, is more lightweight and better suited for general HTML5 parsing and manipulation.

HTMLPurifier has a steeper learning curve due to its numerous configuration options, while html5-php provides a simpler API for basic HTML handling. However, html5-php lacks the robust security features of HTMLPurifier.

In terms of performance, html5-php generally outperforms HTMLPurifier, especially for larger documents. However, HTMLPurifier's thorough sanitization process justifies its slower speed in security-critical applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

UKRAINE NEEDS YOUR HELP NOW!

On 24 February 2022, Russian President Vladimir Putin ordered an invasion of Ukraine by Russian Armed Forces.

Your support is urgently needed.

THANK YOU!


HTML5-PHP

HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has well over five million downloads.

HTML5 provides the following features.

  • An HTML5 serializer
  • Support for PHP namespaces
  • Composer support
  • Event-based (SAX-like) parser
  • A DOM tree builder
  • Interoperability with QueryPath
  • Runs on PHP 5.3.0 or newer

CI Latest Stable Version Code Coverage Scrutinizer Code Quality Stability: Sustained

Installation

Install HTML5-PHP using composer.

By adding the masterminds/html5 dependency to your composer.json file:

{
  "require" : {
    "masterminds/html5": "^2.0"
  },
}

By invoking require command via composer executable:

composer require masterminds/html5

Basic Usage

HTML5-PHP has a high-level API and a low-level API.

Here is how you use the high-level HTML5 library API:

<?php
// Assuming you installed from Composer:
require "vendor/autoload.php";

use Masterminds\HTML5;

// An example HTML document:
$html = <<< 'HERE'
  <html>
  <head>
    <title>TEST</title>
  </head>
  <body id='foo'>
    <h1>Hello World</h1>
    <p>This is a test of the HTML5 parser.</p>
  </body>
  </html>
HERE;

// Parse the document. $dom is a DOMDocument.
$html5 = new HTML5();
$dom = $html5->loadHTML($html);

// Render it as HTML5:
print $html5->saveHTML($dom);

// Or save it to a file:
$html5->save($dom, 'out.html');

The $dom created by the parser is a full DOMDocument object. And the save() and saveHTML() methods will take any DOMDocument.

Options

It is possible to pass in an array of configuration options when loading an HTML5 document.

// An associative array of options
$options = array(
  'option_name' => 'option_value',
);

// Provide the options to the constructor
$html5 = new HTML5($options);

$dom = $html5->loadHTML($html);

The following options are supported:

  • encode_entities (boolean): Indicates that the serializer should aggressively encode characters as entities. Without this, it only encodes the bare minimum.
  • disable_html_ns (boolean): Prevents the parser from automatically assigning the HTML5 namespace to the DOM document. This is for non-namespace aware DOM tools.
  • target_document (\DOMDocument): A DOM document that will be used as the destination for the parsed nodes.
  • implicit_namespaces (array): An assoc array of namespaces that should be used by the parser. Name is tag prefix, value is NS URI.

The Low-Level API

This library provides the following low-level APIs that you can use to create more customized HTML5 tools:

  • A SAX-like event-based parser that you can hook into for special kinds of parsing.
  • A flexible error-reporting mechanism that can be tuned to document syntax checking.
  • A DOM implementation that uses PHP's built-in DOM library.

The unit tests exercise each piece of the API, and every public function is well-documented.

Parser Design

The parser is designed as follows:

  • The Scanner handles scanning on behalf of the parser.
  • The Tokenizer requests data off of the scanner, parses it, clasifies it, and sends it to an EventHandler. It is a recursive descent parser.
  • The EventHandler receives notifications and data for each specific semantic event that occurs during tokenization.
  • The DOMBuilder is an EventHandler that listens for tokenizing events and builds a document tree (DOMDocument) based on the events.

Serializer Design

The serializer takes a data structure (the DOMDocument) and transforms it into a character representation -- an HTML5 document.

The serializer is broken into three parts:

  • The OutputRules contain the rules to turn DOM elements into strings. The rules are an implementation of the interface RulesInterface allowing for different rule sets to be used.
  • The Traverser, which is a special-purpose tree walker. It visits each node node in the tree and uses the OutputRules to transform the node into a string.
  • HTML5 manages the Traverser and stores the resultant data in the correct place.

The serializer (save(), saveHTML()) follows the section 8.9 of the HTML 5.0 spec. So tags are serialized according to these rules:

  • A tag with children: <foo>CHILDREN</foo>
  • A tag that cannot have content: <foo> (no closing tag)
  • A tag that could have content, but doesn't: <foo></foo>

Known Issues (Or, Things We Designed Against the Spec)

Please check the issue queue for a full list, but the following are issues known issues that are not presently on the roadmap:

  • Namespaces: HTML5 only supports a selected list of namespaces and they do not operate in the same way as XML namespaces. A : has no special meaning. By default the parser does not support XML style namespaces via :; to enable the XML namespaces see the XML Namespaces section
  • Scripts: This parser does not contain a JavaScript or a CSS interpreter. While one may be supplied, not all features will be supported.
  • Reentrance: The current parser is not re-entrant. (Thus you can't pause the parser to modify the HTML string mid-parse.)
  • Validation: The current tree builder is not a validating parser. While it will correct some HTML, it does not check that the HTML conforms to the standard. (Should you wish, you can build a validating parser by extending DOMTree or building your own EventHandler implementation.)
    • There is limited support for insertion modes.
    • Some autocorrection is done automatically.
    • Per the spec, many legacy tags are admitted and correctly handled, even though they are technically not part of HTML5.
  • Attribute names and values: Due to the implementation details of the PHP implementation of DOM, attribute names that do not follow the XML 1.0 standard are not inserted into the DOM. (Effectively, they are ignored.) If you've got a clever fix for this, jump in!
  • Processor Instructions: The HTML5 spec does not allow processor instructions. We do. Since this is a server-side library, we think this is useful. And that means, dear reader, that in some cases you can parse the HTML from a mixed PHP/HTML document. This, however, is an incidental feature, not a core feature.
  • HTML manifests: Unsupported.
  • PLAINTEXT: Unsupported.
  • Adoption Agency Algorithm: Not yet implemented. (8.2.5.4.7)

XML Namespaces

To use XML style namespaces you have to configure well the main HTML5 instance.

use Masterminds\HTML5;
$html = new HTML5(array(
    "xmlNamespaces" => true
));

$dom = $html->loadHTML('<t:tag xmlns:t="http://www.example.com"/>');

$dom->documentElement->namespaceURI; // http://www.example.com

You can also add some default prefixes that will not require the namespace declaration, but its elements will be namespaced.

use Masterminds\HTML5;
$html = new HTML5(array(
    "implicitNamespaces"=>array(
        "t"=>"http://www.example.com"
    )
));

$dom = $html->loadHTML('<t:tag/>');

$dom->documentElement->namespaceURI; // http://www.example.com

Thanks to...

The dedicated (and patient) contributors of patches small and large, who have already made this library better.See the CREDITS file for a list of contributors.

We owe a huge debt of gratitude to the original authors of html5lib.

While not much of the original parser remains, we learned a lot from reading the html5lib library. And some pieces remain here. In particular, much of the UTF-8 and Unicode handling is derived from the html5lib project.

License

This software is released under the MIT license. The original html5lib library was also released under the MIT license.

See LICENSE.txt

Certain files contain copyright assertions by specific individuals involved with html5lib. Those have been retained where appropriate.