| 1 |
<?php |
| 2 |
/** |
| 3 |
* ConvertKit HTML Parser class. |
| 4 |
* |
| 5 |
* @package ConvertKit |
| 6 |
* @author ConvertKit |
| 7 |
*/ |
| 8 |
|
| 9 |
/** |
| 10 |
* Provides functionality for parsing HTML content and extracting relevant information. |
| 11 |
* |
| 12 |
* @since 3.0.0 |
| 13 |
*/ |
| 14 |
class ConvertKit_HTML_Parser { |
| 15 |
|
| 16 |
/** |
| 17 |
* DOMDocument. |
| 18 |
* |
| 19 |
* @var DOMDocument |
| 20 |
*/ |
| 21 |
public $html; |
| 22 |
|
| 23 |
/** |
| 24 |
* XPath. |
| 25 |
* |
| 26 |
* @var DOMXPath |
| 27 |
*/ |
| 28 |
public $xpath; |
| 29 |
|
| 30 |
/** |
| 31 |
* Loads HTML content into a DOMDocument and returns the DOMDocument and XPath. |
| 32 |
* |
| 33 |
* @since 3.0.0 |
| 34 |
* |
| 35 |
* @param string $content HTML content to load. |
| 36 |
* @param bool|int $flags DOMDocument flags. |
| 37 |
*/ |
| 38 |
public function __construct( $content, $flags = false ) { |
| 39 |
|
| 40 |
// Wrap content in <html>, <head> and <body> tags with an UTF-8 Content-Type meta tag. |
| 41 |
// Forcibly tell DOMDocument that this HTML uses the UTF-8 charset. |
| 42 |
// <meta charset="utf-8"> isn't enough, as DOMDocument still interprets the HTML as ISO-8859, which breaks character encoding |
| 43 |
// Use of mb_convert_encoding() with HTML-ENTITIES is deprecated in PHP 8.2, so we have to use this method. |
| 44 |
// If we don't, special characters render incorrectly. |
| 45 |
$content = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>' . $content . '</body></html>'; |
| 46 |
|
| 47 |
// Load the HTML into a DOMDocument. |
| 48 |
libxml_use_internal_errors( true ); |
| 49 |
$this->html = new DOMDocument(); |
| 50 |
if ( $flags ) { |
| 51 |
$this->html->loadHTML( $content, $flags ); |
| 52 |
} else { |
| 53 |
$this->html->loadHTML( $content ); |
| 54 |
} |
| 55 |
|
| 56 |
// Load DOMDocument into XPath. |
| 57 |
$this->xpath = new DOMXPath( $this->html ); |
| 58 |
|
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Returns the HTML within the DOMDocument's <body> tag as a string. |
| 63 |
* |
| 64 |
* @since 3.0.0 |
| 65 |
* |
| 66 |
* @return string |
| 67 |
*/ |
| 68 |
public function get_body_html() { |
| 69 |
|
| 70 |
$body = $this->html->getElementsByTagName( 'body' )->item( 0 ); |
| 71 |
|
| 72 |
$html = ''; |
| 73 |
foreach ( $body->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase |
| 74 |
$html .= $this->html->saveHTML( $child ); |
| 75 |
} |
| 76 |
|
| 77 |
return $html; |
| 78 |
|
| 79 |
} |
| 80 |
|
| 81 |
} |
| 82 |
|