how to use dom php parser

前端 未结 4 1598
轻奢々
轻奢々 2020-11-28 13:04

I\'m new to DOM parsing in PHP:
I have a HTML file that I\'m trying to parse. It has a bunch of DIVs like this:

<
4条回答
  •  不知归路
    2020-11-28 13:36

    First i have to tell you that you can't use the same id on two different divs; there are classes for that point. Every element should have an unique id.

    Code to get the contents of the div with id="interestingbox"

    $html = '
    
    
    
    
    Content1
    Content2
    '; $dom_document = new DOMDocument(); $dom_document->loadHTML($html); //use DOMXpath to navigate the html with the DOM $dom_xpath = new DOMXpath($dom_document); // if you want to get the div with id=interestingbox $elements = $dom_xpath->query("*/div[@id='interestingbox']"); if (!is_null($elements)) { foreach ($elements as $element) { echo "\n[". $element->nodeName. "]"; $nodes = $element->childNodes; foreach ($nodes as $node) { echo $node->nodeValue. "\n"; } } } //OUTPUT [div] { Content1 Content2 }

    Example with classes:

    $html = '
    
    
    
    
    Content1
    Content2
    '; //the same as before.. just change the xpath [...] $elements = $dom_xpath->query("*/div[@class='interestingbox']"); [...] //OUTPUT [div] { Content1 Content2 } [div] { a link }

    Refer to the DOMXPath page for more details.

提交回复
热议问题