WP_HTML_Processor::create_fragment( string $html, string $context, string $encoding ): static|null

Creates an HTML processor in the fragment parsing mode.

Description

Use this for cases where you are processing chunks of HTML that will be found within a bigger HTML document, such as rendered block output that exists within a post, the_content inside a rendered site layout.

Fragment parsing occurs within a context, which is an HTML element that the document will eventually be placed in. It becomes important when special elements have different rules than others, such as inside a TEXTAREA or a TITLE tag where things that look like tags are text, or inside a SCRIPT tag where things that look like HTML syntax are JS.

The context value should be a representation of the tag into which the HTML is found. For most cases this will be the body element. The HTML form is provided because a context element may have attributes that impact the parse, such as with a SCRIPT tag and its type attribute.

Current HTML Support

  • The only supported context is <body>, which is the default value.
  • The only supported document encoding is UTF-8, which is the default value.

Parameters

$htmlstringrequired
Input HTML fragment to process.
$contextstringrequired
Context element for the fragment, must be default of <body>.
$encodingstringrequired
Text encoding of the document; must be default of 'UTF-8'.

Return

static|null The created processor if successful, otherwise null.

Source

public static function create_fragment( $html, $context = '<body>', $encoding = 'UTF-8' ) {
	if ( '<body>' !== $context || 'UTF-8' !== $encoding ) {
		return null;
	}

	if ( ! is_string( $html ) ) {
		_doing_it_wrong(
			__METHOD__,
			__( 'The HTML parameter must be a string.' ),
			'6.9.0'
		);
		return null;
	}

	$context_processor = static::create_full_parser( "<!DOCTYPE html>{$context}", $encoding );
	if ( null === $context_processor ) {
		return null;
	}

	while ( $context_processor->next_tag() ) {
		if ( ! $context_processor->is_virtual() ) {
			$context_processor->set_bookmark( 'final_node' );
		}
	}

	if (
		! $context_processor->has_bookmark( 'final_node' ) ||
		! $context_processor->seek( 'final_node' )
	) {
		_doing_it_wrong( __METHOD__, __( 'No valid context element was detected.' ), '6.8.0' );
		return null;
	}

	return $context_processor->create_fragment_at_current_node( $html );
}

Changelog

VersionDescription
6.6.0Returns static instead of self so it can create subclass instances.
6.4.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.