如何使用PHP从另一个PHP文件读取html文件中的特定元素

如何使用PHP从另一个PHP文件读取html文件中的特定元素,php,html,Php,Html,如何使用id读取html元素,该id完全存在于另一个使用php的html文件中。我尝试了“包含”,但它会加载该文件中的所有内容并显示在浏览器中,但我只需要加载一个标记 file1.html <body> <h3 id="title">Title</h3> <p> Some content about the title </> </body> <body> <h3 id="title"&g

如何使用id读取html元素,该id完全存在于另一个使用php的html文件中。我尝试了“包含”,但它会加载该文件中的所有内容并显示在浏览器中,但我只需要加载一个标记

file1.html

<body>
   <h3 id="title">Title</h3>
   <p> Some content about the title </>
</body>
<body>
  <h3 id="title">Title</h3>
  <p> Some content about the title </>
</body>

标题
关于标题的一些内容
file2.php

<?PHP

   #read h3 element using id and display

?>
<?PHP
  $doc = new DOMDocument();
  $doc->loadHTMLFile("file1.html");
  $title = $doc->getElementById("title");
  echo $title->nodeValue;
?>

最简单的解决方案是加载文件(file\u get\u contents)并使用DOM解析它

PHP Dom文档:

该类有一个getElementById方法:

file1.html

<body>
   <h3 id="title">Title</h3>
   <p> Some content about the title </>
</body>
<body>
  <h3 id="title">Title</h3>
  <p> Some content about the title </>
</body>

标题
关于标题的一些内容
file2.php

<?PHP

   #read h3 element using id and display

?>
<?PHP
  $doc = new DOMDocument();
  $doc->loadHTMLFile("file1.html");
  $title = $doc->getElementById("title");
  echo $title->nodeValue;
?>