HTML5-PHP

repository·master·Indexed 23 days ago

https://github.com/masterminds/html5-php

A standards-compliant HTML5 parser and serializer written in PHP. It provides a high-level DOM-based API for parsing HTML strings or files into PHP DOMDocument objects and serializing them back to HTML5, as well as a low-level event-based (SAX-like) API for building customized tools. The library supports configuration for entity encoding, XML-style namespaces, and custom output rules via the RulesInterface.

Tokens
4.6K
Snippets
7
Records
25
Agent score
83%

What's inside html5-php

  1. Understand the relationship between EventHandler and DOMTree

    master

    The EventHandler is the interface used by tree builders. During the tokenization process, the Tokenizer emits tokens to the EventHandler.

    • EventHandler: A generic interface for any component that reacts to tokens.
    • DOMTree: A specific implementation of an EventHandler that builds a DOM tree. The output of the DOMTree builder is a DOMDocument.
  2. Customize serialization with Output Rules

    master

    Serialization logic is governed by implementations of RulesInterface.

    • Default Behavior: The OutputRules class is the default implementation, which converts a DOM structure into HTML5 as-is.
    • Customization: You can provide different implementations of RulesInterface to change how specific DOM elements are converted into HTML5 strings.
  3. How the HTML5 parser and serializer are designed

    master

    HTML5-PHP is composed of several layers for both parsing and serialization:

    Parser Architecture

    • Scanner: Handles the raw scanning of the input.
    • Tokenizer: A recursive descent parser that requests data from the scanner, classifies it, and sends it to an EventHandler.
    • EventHandler: Receives notifications and data for specific semantic events during tokenization.
    • DOMBuilder: An implementation of EventHandler that listens to tokenization events to build a DOMDocument tree.

    Serializer Architecture

    The serializer transforms a DOMDocument into an HTML5 character representation using three components:

    • OutputRules: Implements RulesInterface to define how DOM elements are converted to strings.
    • Traverser: A specialized tree walker that visits every node and applies OutputRules.
    • HTML5: The main class that manages the Traverser and stores the resulting data.

    Note: The serializer follows Section 8.9 of the HTML 5.0 spec regarding tag serialization (e.g., handling tags with children vs. tags that cannot have content).

  4. Use DOMDocument as the parsed output

    master

    The final output of the parsing process is a DOMDocument (or a DOMDocumentFragment if parsing an HTML5 fragment).

    Because the library uses PHP's built-in DOMDocument class (part of libxml), the resulting objects are compatible with standard PHP XML/HTML processing tools such as:

    • SimpleXML
    • QueryPath
    • Other libxml-based tools.
  5. Understand the HTML5-PHP Parser Model

    master

    The parser follows the HTML5 specification (section 8.2.1) through a multi-stage pipeline that transforms raw input into a structured document. The flow is as follows:

    1. InputStream: Reads the raw input (strings or files).
    2. Scanner: Breaks the stream into characters.
    3. Tokenizer: Groups characters into syntactic tokens (following section 8.4 of the spec).
    4. Tree Builder (EventHandler): Organizes tokens into a tree of objects.
    5. DOM Document: The final state of the parsed document.

    This architecture allows the library to separate the mechanical process of reading and tokenizing from the logic of building a tree structure.

  6. Understand the HTML5 Serializer (Writer) Model

    master

    The serializer converts DOMDocument, DOMDocumentFragment, and DOMNodeList into HTML5 strings or files. The process follows a layered architecture:

    1. HTML5 Class: The top-level interface used to initiate the saving process.
    2. Traverser: Walks the DOM tree to find each element.
    3. Rules: Uses implementations of RulesInterface to convert DOM elements into their corresponding HTML5 string representations.
    4. HTML5 String: The final result, which is either an HTML5 string or a file saved to disk.
  7. Install HTML5-PHP via Composer

    master

    You can install HTML5-PHP using Composer by either adding it to your composer.json file or by running the require command in your terminal.

    Option 1: Update composer.json Add masterminds/html5 with a version constraint of ^2.0 to your dependencies.

    Option 2: Use the CLI Run the following command in your project root:

    composer require masterminds/html5
  8. Enable XML-style namespaces in HTML5-PHP

    master

    By default, the parser does not support XML-style namespaces using the : prefix. To enable this, you must pass xmlNamespaces => true in the configuration array passed to the HTML5 constructor.

    You can also use implicitNamespaces to define default prefixes so that elements are namespaced even without an explicit declaration in the source HTML.

    use Masterminds\HTML5;
    
    // Enable XML namespaces
    $html = new HTML5(array(
        "xmlNamespaces" => true
    ));
    
    $dom = $html->loadHTML('<t:tag xmlns:t="http://www.example.com"/>');
    
    echo $dom->documentElement->namespaceURI; // http://www.example.com
    use Masterminds\HTML5;
    
    // Use implicit namespaces to avoid needing declarations in the HTML
    $html = new HTML5(array(
        "implicitNamespaces"=>array(
            "t"=>"http://www.example.com"
        )
    ));
    
    $dom = $html->loadHTML('<t:tag/>');
    echo $dom->documentElement->namespaceURI; // http://www.example.com
  9. Basic Usage of the HTML5 High-Level API

    master

    The high-level Masterminds\HTML5 API allows you to parse HTML strings into a DOMDocument and serialize them back to HTML5.

    1. Instantiate Masterminds\HTML5.
    2. Use loadHTML($html) to parse an HTML string. This returns a standard PHP DOMDocument object.
    3. Use saveHTML($dom) to get the serialized HTML string.
    4. Use save($dom, 'filename.html') to write the document directly to a file.
    <?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');
  10. Configure HTML5 parser options

    master

    You can pass an associative array of configuration options to the Masterminds\HTML5 constructor to customize parsing and serialization behavior.

    Supported options:

    • encode_entities (boolean): If true, the serializer aggressively encodes characters as entities. If false, it only encodes the bare minimum.
    • disable_html_ns (boolean): Prevents the parser from automatically assigning the HTML5 namespace to the DOM document. Use this for non-namespace aware DOM tools.
    • target_document (\DOMDocument): A specific DOMDocument instance to be used as the destination for parsed nodes.
    • implicit_namespaces (array): An associative array where the key is the tag prefix and the value is the Namespace URI. These namespaces will be used by the parser without requiring explicit declarations in the HTML.
    // 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);
  11. Known limitations and design decisions in HTML5-PHP

    master

    When using HTML5-PHP, be aware of the following design choices and limitations:

    • Namespaces: Only a selected list of namespaces is supported. By default, it does not support XML-style : namespaces unless configured.
    • Scripts: There is no JavaScript or CSS interpreter included.
    • Reentrance: The parser is not re-entrant (you cannot pause parsing to modify the string mid-parse).
    • Validation: The DOMBuilder is not a validating parser; it corrects some HTML but does not strictly check conformance to the standard.
    • Attribute Names: Due to PHP's internal DOM implementation, attribute names that do not follow the XML 1.0 standard are ignored.
    • Unsupported Features: HTML manifests, PLAINTEXT content types, and the Adoption Agency Algorithm are currently unsupported.