


PHP parsing html class library simple_html_dom (detailed introduction)_PHP tutorial
Download address: https://github.com/samacs/simple_html_dom
The parser not only helps us verify html documents; it can also parse html documents that do not comply with W3C standards. It uses an element selector similar to jQuery to find and locate elements by their id, class, tag, etc.; it also provides the functions of adding, deleting, and modifying the document tree. Of course, such a powerful html Dom parser is not perfect; you need to be very careful about memory consumption during use. However, don’t worry; in this article, I will explain how to avoid consuming too much memory at the end.
Start using
After uploading a class file, there are three ways to call this class:
Load html document from url
Load html document from string
Load html document from file
/ / Create a new Dom instance
$html = new simple_html_dom();
// Load from url
$html->load_file('http://www.jb51.net') ;
//Load from string
$html->load('Load html document demo from string
//Load from file
$html->load_file('path/file/test.html');
?>
If you load an html document from a string, you need to download it from the Internet first. It is recommended to use cURL to grab html documents and load them into the DOM.
Find html elements
You can use the find function to find elements in the html document. The returned result is an array containing objects. We use the functions in the HTML DOM parsing class to access these objects. Here are a few examples:
//Find hyperlink elements in html documents
$a = $html->find('a');
//Find The (N)th hyperlink in the document, if not found, returns an empty array.
$a = $html->find('a', 0);
//The search id is main The div element
$main = $html->find('div[id=main]',0);
// Find all div elements containing the id attribute
$divs = $html->find('div[id]');
// Find all elements containing the id attribute
$divs = $html->find('[id]' );
?>
You can also use a jQuery-like selector to find positioned elements:
// Find the element with id='#container'
$ret = $html->find('#container');
// Find all elements with class=foo
$ret = $html->find('.foo');
// Find multiple html tags
$ ret = $html->find('a, img');
// You can also use it like this
$ret = $html->find('a[title], img[title ]');
?>
The parser supports searching for child elements
// Find all li items in the ul list
$ret = $html->find('ul li');
//Find the li item with class=selected specified in the ul list
$ret = $html->find('ul li.selected');
?>
If you find this troublesome, you can use built-in functions to easily locate the parent, child and adjacent elements of an element
// Returns the parent element
$e->parent;
// Returns the array of child elements
$ e->children;
// Return the specified child element by index number
$e->children(0);
// Return the first resource speed
$e->first_child ();
// Return the last child element
$e->last _child ();
// Return the previous adjacent element
$e->prev_sibling ();
//Return the next adjacent element
$e->next_sibling ();
?>
Element Attribute Operations
Use simple regular expressions to operate attribute selectors.
[attribute] - selects html elements that contain a certain attribute
[attribute=value] - selects all html elements with a specified value attribute
[attribute!=value] - selects all html elements with a non-specified value attribute
[attribute^=value] - selects all html elements with attributes starting with a specified value
[attribute$=value] selects all html elements with attributes ending with a specified value
[attribute*=value] - selects all elements containing The html element
that specifies the value attribute calls the element attribute in the parser
. The element attribute in the DOM is also an object:
// In this example, the anchor link value of $a is assigned to the $link variable
$link = $a->href;
?>
or:
$ link = $html->find('a',0)->href;
?
Each object has 4 basic object properties:
tag – return html tag name
innertext - returns innerHTML
outertext - returns outerHTML
plaintext - returns the text in the html tag
Editing elements in the parser
The usage of editing element attributes is similar to calling them of:
//Assign the anchor link of $a New value
$a->href = 'http://www.jb51.net';
// Delete anchor link
$a->href = null;
//Detect whether there is an anchor link
if(isset($a->href)) {
//Code
}
?>
There is no special method to add or delete elements in the parser, but you can use it differently:
// Encapsulation element
$e->outertext = '
// Delete element
$e->outertext = '';
// Add element
$e->outertext = $e->outertext . '
// Insert element
$e->outertext = '
?
Saving the modified html DOM document is also very simple:
$doc = $html;
// Output
echo $doc;
?>
How to avoid the parser consuming too much memory
At the beginning of this article, the author mentioned the problem of the Simple HTML DOM parser consuming too much memory. If the php script takes up too much memory, it will cause the website to stop responding and a series of serious problems. The solution is also very simple. After the parser loads the HTML document and uses it, remember to clean up this object. Of course, don't take the problem too seriously. If only 2 or 3 documents are loaded, cleaning or not cleaning does not make much difference. When you load 5, 10 or more documents, it is absolutely your responsibility to clear the memory after using one ^_^
$html->clear();
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
