2012-05-10 72 views
0

我想在下面的帖子xml中選擇第一個img的src。如何在使用php的Tumblr xml文件中選擇img src?

<post> 
<regular-title>Testing 1</regular-title> 
<regular-body> 
<p>This is a test for projects on the website</p> 
<p><img src="http://media.tumblr.com/tumblr_m3t0r3saXy1rocfxw.jpg"/></p> 
<p><img src="http://media.tumblr.com/tumblr_m3t0s6bPyw1rocfxw.jpg"/></p> 
</regular-body> 
</post> 

我可以選擇使用php的標題和發佈文本,但我還沒有能夠選擇img或其src。

$title = $xml->posts->post->{'regular-title'}; 
$img = $xml->posts->post->{'regular-body'}->??????; 
$post = $xml->posts->post->{'regular-body'}; 

我使用正確的方法來選擇IMG或有另一種方式嗎?

回答

0
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $xml->posts->post->{'regular-body'}, $matches); 
$first_img = $matches[1][0]; 
if(!empty($first_img)) 
    return $first_img; 
return 'no image url.png'; 

這應該只是罰款爲你

+0

感謝您的幫助。第一次工作! – olouali

0

你可以很容易使用DOM classes

$xml = '<post> 
    <regular-title>Testing 1</regular-title> 
    <regular-body> 
    <p>This is a test for projects on the website</p> 
    <p><img src="http://media.tumblr.com/tumblr_m3t0r3saXy1rocfxw.jpg"/></p> 
    <p><img src="http://media.tumblr.com/tumblr_m3t0s6bPyw1rocfxw.jpg"/></p> 
    </regular-body> 
    </post>'; 
$dom = new DOMDocument(); 
$dom->loadXML($xml); 

$images = $dom->getElementsByTagName("img"); 
$firstImage = $images->item(0); //get the first img tag 
$src = $firstImage->getAttribute("src");