0

我正在尝试为以下帖子 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 还是有其他方法?

4

2 回答 2

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

这对你来说应该很好

于 2012-05-10T14:18:03.383 回答
0

您可以使用DOM 类轻松获得它:

$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");
于 2012-05-10T14:32:50.547 回答