如何在 PHP 中解析 HTML? [英] How to parse HTML in PHP?
问题描述
我知道我们可以使用 PHP DOM 使用 PHP 解析 HTML.我在 Stack Overflow 上也发现了很多问题.但我有一个特定的要求.我有一个像下面这样的 HTML 内容
I know we can use PHP DOM to parse HTML using PHP. I found a lot of questions here on Stack Overflow too. But I have a specific requirement. I have an HTML content like below
<p class="Heading1-P">
<span class="Heading1-H">Chapter 1</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 1</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 2</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 2</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 3</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 3</span>
</p>
我想解析上面的 HTML 并将内容保存到两个不同的数组中,例如:
I want to parse the above HTML and save the content into two different arrays like:
$heading
和 $content
$heading = array('Chapter 1','Chapter 2','Chapter 3');
$content = array('This is chapter 1','This is chapter 2','This is chapter 3');
我可以简单地使用 jQuery 来实现这一点.但我不确定,这是否是正确的方法.如果有人能指出我正确的方向,那就太好了.提前致谢.
I can achieve this simply using jQuery. But I am not sure, if that's the right way. It would be great if someone can point me to the right direction. Thanks in advance.
推荐答案
试试看PHP Simple HTML DOM Parser一个>
它具有类似于 jQuery 的出色语法,因此您可以轻松地通过 ID 或类选择您想要的任何元素
It has brilliant syntax similar to jQuery so you can easily select any element you want by ID or class
// include/require the simple html dom parser file
$html_string = '
<p class="Heading1-P">
<span class="Heading1-H">Chapter 1</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 1</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 2</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 2</span>
</p>
<p class="Heading1-P">
<span class="Heading1-H">Chapter 3</span>
</p>
<p class="Normal-P">
<span class="Normal-H">This is chapter 3</span>
</p>';
$html = str_get_html($html_string);
foreach($html->find('span') as $element) {
if ($element->class === 'Heading1-H') {
$heading[] = $element->innertext;
}else if($element->class === 'Normal-H') {
$content[] = $element->innertext;
}
}
这篇关于如何在 PHP 中解析 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!