Home / Admin / HTML inside PHP
Duplicate Snippet

Embed Snippet on Your Site

HTML inside PHP

How to output HTML inside PHP.

Code Preview
php
<?php
// ❌ The output of this function is not readable
public function displayHtml() {
	//some logic here
	echo '<div class="container">';
	echo '<span class="wrapper">';
	echo '<i class="fas fa-home"></i>';
	echo __('Some text', 'duplicator-pro');
	echo '</span></div>';
}
// ❌ This function needs to escape large amount of HTML, which increases the possibility of an error
public function displayHtml() {
	//some logic here
	$result  = '<div class="container">';
	$result .= '<span class="wrapper">';
	$result .= '<i class="fas fa-home"></i>';
	$result .= __('Some text', 'duplicator-pro');
	$result .= '</span></div>';
	
	echo wp_kses(
		$result,
		[
			'div' => [
				'class' => [],
			],
			'i' => [
				'class' => [],
			],
			'span' => [
				'class' => [],
			],
		]
	);
}
	
// ✅ Closing php tags before outputting a large amount of HTML makes the code more readable
public function displayHtml() {
	//some logic here
	?>
	<div class="container">
		<span class="wrapper">
			<i class="fas fa-home"></i>
			<?php esc_html_e('Some text', 'duplicator-pro'); ?>
		</span>
	</div>
<?php
}

Comments

Add a Comment