解析HTML字符串的PHP方法

7

我有一个包含以下HTML的PHP字符串,我从RSS源中检索到。我使用simplepie,但找不到其他分割从<description>获取的这两个数据集的方法。如果有人知道在simplepie中选择子元素的方法,那就太好了。

<div style="example"><div style="example"><img title="example" alt="example" src="example.jpg"/></div><div style="example">EXAMPLE TEXT</div></div>

to:

$image = '<img title="example" alt="example" src="example.jpg">';
$description = 'EXAMPLE TEXT';

https://dev59.com/pWw05IYBdhLWcg3wnjPC - merrais
3个回答

9
$received_str = 'Your received html';

$html = str_get_html($received_str);

//Image tag
$img_tag = $html->find("img", 0)->outertext;

//Example Text
$example_text = $html->find('div[style=example]', 0)->last_child()->innertext;

请查看这里:http://simplehtmldom.sourceforge.net/manual.htm


刚刚测试了“Simple html DOM”,在大文件上不太可靠。在我的情况下,我有一个包含2800个div的文件,并且想要在它们之间循环,但只找到了前21个出现的div... - Power Engineering

3
尝试使用 Simple HTML Dom解析器
// Create DOM from HTML string
$html = str_get_html('Your HTML here');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Description
$description = $html->find('div[style=example]');  

div[style=example] 匹配了三个节点。 - Lightness Races in Orbit

1

尝试使用strip_tags:

<?php
    $html ='<div style="example"><div style="example"><img title="example" alt="example" src="example.jpg"/></div><div style="example">EXAMPLE TEXT</div></div>';
    $html = strip_tags($html,'<img>');
    // $html == '<img title="example" alt="example" src="example.jpg">'
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接