Parsing HTML with PHP implementation code _php Tips

Source: Internet
Author: User
Recently want to use PHP to write a crawler, you need to parse the HTML, on the SourceForge to find a project called PHP simple HTML DOM Parser, it can be in a similar way jquery through the CSS selector to return the specified DOM elements, the function is very powerful.
First, introduce the simple_html_dom.php file at the beginning of the program.
Copy Code code as follows:

Include_once (' simple_html_dom.php ');

PHP Simple HTML DOM Parser provides 3 ways to create a DOM object
Copy Code code as follows:

Create a DOM object from a string
$html = str_get_html (' Create a DOM object from a URL
$html = file_get_html (' http://www.google.com/');
Create a DOM object from a HTML file
$html = file_get_html (' test.htm ');

After you get the DOM object, you can do all sorts of things.
Copy Code code as follows:

Find all anchors, returns a array of element objects
$ret = $html->find (' a ');
Find (N) th anchor, returns element object or null if not found (zero based)
$ret = $html->find (' A ', 0);
Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find (' A ',-1);
Find all <div> with the id attribute
$ret = $html->find (' div[id] ');
Find all <div> which attribute Id=foo
$ret = $html->find (' div[id=foo] ');

You can use a variety of CSS selectors, just as you would for Dom in jquery. In addition, there are two special properties to get text and annotation content
Copy Code code as follows:

Find all text blocks
$es = $html->find (' text ');
Find all comment (<!--...-->) blocks
$es = $html->find (' comment ');

Of course, it's similar to jquery,php simple HTML DOM parser also supports chained operations, and a variety of easy ways to access DOM elements
Copy Code code as follows:

Example
echo $html->find ("#div1", 0)->children (1)->children (1)->children (2)->id;
Or
echo $html->getelementbyid ("Div1")->childnodes (1)->childnodes (1)->childnodes (2)->getattribute (' Id ');

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.