2011-05-21 121 views
5

我有一個PHP字符串,其中包含下面的HTML我從RSS提要檢索。我正在使用簡單的餅圖,無法找到從<description>獲得的分割這兩個數據集的其他方式。如果有人知道在簡單的餡餅中選擇一個很棒的孩子的方法。解析HTML字符串的PHP方法

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

http://stackoverflow.com/questions/7124823/file-get-html-displays-fatal -error-call-to-undefined-function – merrais 2017-03-10 22:30:45

回答

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

2

嘗試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]'); 
+0

'div [style = example]'匹配三個節點。 – 2011-05-21 17:35:54

0
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"> 
    ?> 
+0

[不完全](http://www.ideone.com/bpWIA),但這是朝正確方向邁出的一步。 – 2011-05-21 17:35:15