如何解析php代码中的html内容?

时间:2015-12-23 08:42:32

标签: php html

如何分别解析以下代码中每个标题的内容。

$str="<html>
          <body>
          <h1>Java</h1>
          <p>Java is a platform independent object oriented programming language</p>
          <h2>Html</h2>
          <p>HTML is a markup language for describing web documents</p>
          <h3>Php</h3>
          <p>Php is simple</p>
          </body>
          </html>";

1 个答案:

答案 0 :(得分:2)

使用DOMDocument&amp; XPath很简单。

$str="
<html>
    <body>
        <h1>Java</h1>
        <p>Java is a platform independent object oriented programming language</p>
        <h2>Html</h2>
        <p>HTML is a markup language for describing web documents</p>
        <h3>Php</h3>
        <p>Php is simple</p>
    </body>
</html>";

$dom=new DOMDocument;
$dom->loadHTML( $str );
$xp=new DOMXPath( $dom );
$col=$xp->query('//h1|//h2|//h3');
foreach( $col as $node ) echo $node->nodeValue;