Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP way of parsing HTML string

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';
like image 978
ThomasReggi Avatar asked May 21 '11 16:05

ThomasReggi


People also ask

How parse HTML in PHP?

To add the dynamic data (HTML content) at a certain point in PHP code, we need parsing. For example: For adding the data (info) in the form of HTML, we need to make that dynamic template in string and then convert it to HTML. How should we do parsing? We should use loadHTML() function for parsing.

How HTML code is parsed?

HTML parsing involves tokenization and tree construction. HTML tokens include start and end tags, as well as attribute names and values. If the document is well-formed, parsing it is straightforward and faster. The parser parses tokenized input into the document, building up the document tree.

Can we parse HTML?

If you just want to parse HTML and your HTML is intended for the body of your document, you could do the following : (1) var div=document. createElement("DIV"); (2) div. innerHTML = markup; (3) result = div. childNodes; --- This gives you a collection of childnodes and should work not just in IE8 but even in IE6-7.


2 Answers

$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

like image 60
Sadat Avatar answered Nov 07 '22 03:11

Sadat


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]');  
like image 21
Naveed Avatar answered Nov 07 '22 02:11

Naveed