使用implexml_Load解析XML

2022-04-13 00:00:00 xml php simplexml

我正在尝试分析XML,但在尝试获取图像URL时遇到问题。

我的XML是:

<entry>
<title>The Title</title>
<id>http://example.com/post/367327.html</id>
<summary>Some extra text</summary>
<link rel="enclosure" href="http://example.com/photos/f_0px_30px/image687.jpg" type="image/jpeg"  length="" /> 
</entry>

到目前为止,我使用以下代码来获取其他数据:

$url = "http://msdssite.com/feeds/xml/myxml.xml";
$xml = simplexml_load_file($url);

foreach($xml->entry as $PRODUCT)
{
$my_title = trim($PRODUCT->title);
$url = trim($PRODUCT->id);
$myimg = $PRODUCT->link;
}

我如何才能从中解析href<link rel="enclosure" href="http://example.com/photos/f_0px_30px/image687.jpg" type="image/jpeg" length="" />


解决方案

由于您的条目似乎可以包含几个link标记,您需要检查type属性是否具有值image/jpeg,以确保获得指向图像的链接:

ini_set("display_errors", "On");

$feedURL = 'http://OLDpost.gr/feeds/xml/category-takhs-xatzhs.xml';

$feed = simplexml_load_file($feedURL);

$results = array();

foreach($feed->entry as $entry) {
    $result = array('title' => (string)$entry->title,
                    'url'   => (string)$entry->id);

    $links = $entry->link;
    foreach ($links as $link) {
        $linkAttr = $link->attributes();
        if (isset($linkAttr['type']) && $linkAttr['type']=='image/jpeg') {
            $result['img'] = (string)$linkAttr['href'];
            break;
        }
    }
    $results[] = $result;
}

print_r($results);

注意,像这样使用implexml(Foreach循环查找好的链接标记)不是很方便。最好使用XPath查询:

foreach($feed->entry as $entry) {
   $entry->registerXPathNamespace('e', 'http://www.w3.org/2005/Atom');
   $results[] = array(
     'title' => (string)$entry->title,
     'url'   => (string)$entry->id,
     'img'   => (string)$entry->xpath('e:link[@type="image/jpeg"]/@href')[0][0]
   );
}

相关文章