PHP way of parsing HTML string

坚强是说给别人听的谎言 提交于 2019-12-30 19:26:43

问题


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.

<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';

回答1:


$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;

See Here: http://simplehtmldom.sourceforge.net/manual.htm




回答2:


Try Simple HTML Dom Parser

// 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]');  



回答3:


try using 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">
    ?>


来源:https://stackoverflow.com/questions/6083076/php-way-of-parsing-html-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!