php PHP解析HTML字符串的方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6083076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP way of parsing HTML string
提问by ThomasReggi
I have a php string that contains the below HTML I am retrieving from an RSS feed. I am using simple pie and cant find any other way of splitting these two datasets it gets from <description>
. If anyone knows of a way in simple pie to select children that would be great.
我有一个 php 字符串,其中包含我从 RSS 提要中检索的以下 HTML。我正在使用简单的馅饼,但找不到任何其他方式来拆分它从<description>
. 如果有人知道用简单的馅饼来选择孩子的方法,那就太好了。
<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';
回答by Sadat
$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;
回答by Naveed
// 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]');
回答by The Mask
try using strip_tags:
尝试使用 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">'
?>