Core class used to safely parse and modify an HTML document.
Description
The HTML Processor class properly parses and modifies HTML5 documents. It supports a subset of the HTML5 specification, and when it encounters unsupported markup, it aborts early to avoid unintentionally breaking the document. The HTML Processor should never break an HTML document. While the WP_HTML_Tag_Processor is a valuable tool for modifying attributes on individual HTML tags, the HTML Processor is more capable and useful for the following operations: <ul> <li>Querying based on nested HTML structure.</li> </ul> Eventually the HTML Processor will also support: <ul> <li>Wrapping a tag in surrounding HTML.</li> <li>Unwrapping a tag by removing its parent.</li> <li>Inserting and removing nodes.</li> <li>Reading and changing inner content.</li> <li>Navigating up or around HTML structure.</li> </ul> <h2>Usage</h2> Use of this class requires three steps: <ol> <li>Call a static creator method with your input HTML document.</li> <li>Find the location in the document you are looking for.</li> <li>Request changes to the document at that location.</li> </ol> Example: $processor = WP_HTML_Processor::create_fragment( $html );
if ( $processor->next_tag( array( 'breadcrumbs' => array( 'DIV', 'FIGURE', 'IMG' ) ) ) ) {
$processor->add_class( 'responsive-image' );
} <h4>Breadcrumbs</h4> Breadcrumbs represent the stack of open elements from the root of the document or fragment down to the currently-matched node, if one is currently selected. Call WP_HTML_Processor::get_breadcrumbs() to inspect the breadcrumbs for a matched tag. Breadcrumbs can specify nested HTML structure and are equivalent to a CSS selector comprising tag names separated by the child combinator, such as "DIV > FIGURE > IMG". Since all elements find themselves inside a full HTML document when parsed, the return value from get_breadcrumbs() will always contain any implicit outermost elements. For example, when parsing with create_fragment() in the BODY context (the default), any tag in the given HTML document will contain array( 'HTML', 'BODY', … ) in its breadcrumbs. Despite containing the implied outermost elements in their breadcrumbs, tags may be found with the shortest-matching breadcrumb query. That is, array( 'IMG' ) matches all IMG elements and array( 'P', 'IMG' ) matches all IMG elements directly inside a P element. To ensure that no partial matches erroneously match it's possible to specify in a query the full breadcrumb match all the way down from the root HTML element. Example: $html = '<figure><img><figcaption>A <em>lovely</em> day outside</figcaption></figure>';
// ----- Matches here.
$processor->next_tag( array( 'breadcrumbs' => array( 'FIGURE', 'IMG' ) ) );
$html = '<figure><img><figcaption>A <em>lovely</em> day outside</figcaption></figure>';
// ---- Matches here.
$processor->next_tag( array( 'breadcrumbs' => array( 'FIGURE', 'FIGCAPTION', 'EM' ) ) );
$html = '<div><img></div><img>';
// ----- Matches here, because IMG must be a direct child of the implicit BODY.
$processor->next_tag( array( 'breadcrumbs' => array( 'BODY', 'IMG' ) ) ); <h2>HTML Support</h2> This class implements a small part of the HTML5 specification.It's designed to operate within its support and abort early whenever encountering circumstances it can't properly handle. This is the principle way in which this class remains as simple as possible without cutting corners and breaking compliance. <h3>Supported elements</h3> If any unsupported element appears in the HTML input the HTML Processor will abort early and stop all processing. This draconian measure ensures that the HTML Processor won't break any HTML it doesn't fully understand. The HTML Processor supports all elements other than a specific set: <ul> <li>Any element inside a TABLE.</li> <li>Any element inside foreign content, including SVG and MATH.</li> <li>Any element outside the IN BODY insertion mode, e.g. doctype declarations, meta, links.</li> </ul> <h3>Supported markup</h3> Some kinds of non-normative HTML involve reconstruction of formatting elements and re-parenting of mis-nested elements. For example, a DIV tag found inside a TABLE may in fact belong <em>before</em> the table in the DOM. If the HTML Processor encounters such a case it will stop processing. The following list illustrates some common examples of unexpected HTML inputs that the HTML Processor properly parses and represents: <ul> <li>HTML with optional tags omitted, e.g. <p>one<p>two.</li> <li>HTML with unexpected tag closers, e.g. <p>one </span> more</p>.</li> <li>Non-void tags with self-closing flag, e.g. <div/>the DIV is still open.</div>.</li> <li>Heading elements which close open heading elements of another level, e.g. <h1>Closed by </h2>.</li> <li>Elements containing text that looks like other tags but isn't, e.g. <title>The <img> is plaintext</title>.</li> <li>SCRIPT and STYLE tags containing text that looks like HTML but isn't, e.g. <script>document.write('<p>Hi</p>');</script>.</li> <li>SCRIPT content which has been escaped, e.g. <script><!-- document.write('<script>console.log("hi")</script>') --></script>.</li> </ul> <h3>Unsupported Features</h3> This parser does not report parse errors. Normally, when additional HTML or BODY tags are encountered in a document, if there are any additional attributes on them that aren't found on the previous elements, the existing HTML and BODY elements adopt those missing attribute values. This parser does not add those additional attributes. In certain situations, elements are moved to a different part of the document in a process called "adoption" and "fostering." Because the nodes move to a location in the document that the parser had already processed, this parser does not support these situations and will bail.
Properties · 9
$stateWP_HTML_Processor_Stateprivate
Holds the working state of the parser, including the stack of open elements and the stack of active formatting elements.
$bookmark_counterintprivate
Used to create unique bookmark names.
$last_errorstring|nullprivate
Stores an explanation for why something failed, if it did.
next_token()Finds the next token in the HTML document.
next_visitable_token()Ensures internal accounting is maintained for HTML semantic rules while the underlying Tag Processor class is seeking to a bookmark.
is_tag_closer()Indicates if the current tag token is a tag closer.
is_virtual()Indicates if the currently-matched token is virtual, created by a stack operation while processing HTML, rather than a token found in the HTML text itself.
matches_breadcrumbs()Indicates if the currently-matched tag matches the given breadcrumbs.
expects_closer()Indicates if the currently-matched node expects a closing token, or if it will self-close on the next step.
step()Steps through the HTML document and stop at the next tag, if any.
get_breadcrumbs()Computes the HTML breadcrumbs for the currently-matched node, if matched.
get_current_depth()Returns the nesting depth of the current location in the document.
normalize()Normalizes an HTML fragment by serializing it.
serialize()Returns normalized HTML for a fragment by serializing it.
143classWP_HTML_ProcessorextendsWP_HTML_Tag_Processor{144/**145 * The maximum number of bookmarks allowed to exist at any given time.146 *147 * HTML processing requires more bookmarks than basic tag processing,148 * so this class constant from the Tag Processor is overwritten.149 *150 * @since 6.4.0151 *152 * @var int153 */154constMAX_BOOKMARKS=100;155156/**157 * Holds the working state of the parser, including the stack of158 * open elements and the stack of active formatting elements.159 *160 * Initialized in the constructor.161 *162 * @since 6.4.0163 *164 * @var WP_HTML_Processor_State165 */166private$state;167168/**169 * Used to create unique bookmark names.170 *171 * This class sets a bookmark for every tag in the HTML document that it encounters.172 * The bookmark name is auto-generated and increments, starting with `1`. These are173 * internal bookmarks and are automatically released when the referring WP_HTML_Token174 * goes out of scope and is garbage-collected.175 *176 * @since 6.4.0177 *178 * @see WP_HTML_Processor::$release_internal_bookmark_on_destruct179 *180 * @var int181 */182private$bookmark_counter=0;183184/**185 * Stores an explanation for why something failed, if it did.186 *187 * @see self::get_last_error188 *189 * @since 6.4.0190 *191 * @var string|null192 */193private$last_error=null;194195/**196 * Stores context for why the parser bailed on unsupported HTML, if it did.197 *198 * @see self::get_unsupported_exception199 *200 * @since 6.7.0201 *202 * @var WP_HTML_Unsupported_Exception|null203 */204private$unsupported_exception=null;205206/**207 * Releases a bookmark when PHP garbage-collects its wrapping WP_HTML_Token instance.208 *209 * This function is created inside the class constructor so that it can be passed to210 * the stack of open elements and the stack of active formatting elements without211 * exposing it as a public method on the class.212 *213 * @since 6.4.0214 *215 * @var Closure|null216 */217private$release_internal_bookmark_on_destruct=null;218219/**220* Stores stack events which arise during parsing of the221*HTML document, which will then supply the "match" events.222*
History
Introduced in 6.4.0. 5 changes between 6.7.7 and 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
7.1.0
Method escape_text_for_serialization() added.verified against source
7.1.0
Method in_body_any_other_end_tag() added.verified against source
7.1.0
Method step_in_select() removed.verified against source
7.1.0
Method step_in_select_in_table() removed.verified against source
6.8.8
Method create_fragment_at_current_node() added.verified against source
6.4.0
Introduced.from the docblock
About this page
Parsed data
Generated from the wordpress-develop 6.8.8 tag, from src/wp-includes/html-api/class-wp-html-processor.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.