为了账号安全,请及时绑定邮箱和手机立即绑定

使用 PHP 从新闻网站访问 XML 元素和名称空间

使用 PHP 从新闻网站访问 XML 元素和名称空间

炎炎设计 2023-10-04 14:23:48
file_get_contents我使用和 尝试检索 xml 内容SimpleXMLElement,但我得到的 PHP 数组仅包含 XML 数据的父元素。使用时simplexml_load_string我得到这个PHP 数组:SimpleXMLElement Object(    [url] => Array        (            [0] => SimpleXMLElement Object                (                    [loc] => https://www.lemonde.fr/culture/article/2020/03/22/crise-sanitaire-malgre-les-annonces-du-gouvernement-les-intermittents-du-spectacle-restent-inquiets_6034031_3246.html                    [lastmod] => 2020-03-12T20:00:12+01:00                )            [1] => SimpleXMLElement Object                (                    [loc] => https://www.lemonde.fr/climat/article/2020/03/22/l-eau-a-l-epreuve-des-changements-climatiques_6034029_1652612.html                    [lastmod] => 2020-03-22T16:34:35+01:00<                )            [2] => SimpleXMLElement Object                (                    [loc] => https://www.lemonde.fr/journal-blouses-blanches/article/2020/03/22/journal-de-crise-des-blouses-blanches-la-consigne-est-de-se-cacher-quand-le-brancard-passe_6034028_6033712.html                    [lastmod] => 2020-03-22T16:02:29+01:00                )我需要检索特定元素,那么如何才能访问它们呢?提前致谢!
查看完整描述

1 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

您可以使用 XPath 进入文档:


$xml = simplexml_load_string($content);

$xml->registerXPathNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9'); // xpath need to have an 'alias' to query the anonymous namespace


$urls = $xml->xpath('//s:url'); // retrieve all url items


foreach($urls as $url) // loop over each url item

{

    $url->registerXPathNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');


    // string conversion gives you only the content of the node

    $title = (string) $url->xpath('news:news/news:title')[0];

    $loc = (string) $url->xpath('s:loc')[0];

    $lastmod = (string) $url->xpath('s:lastmod')[0];

    $pubDate = (string) $url->xpath('news:news/news:publication_date')[0] ;


    echo $title . PHP_EOL; 

    echo $loc . PHP_EOL ; 

    echo $lastmod . PHP_EOL ; 

    echo $pubDate . PHP_EOL; 

}

//意味着您查看文档中任何位置的所有具有该名称的节点,single/意味着您查看该节点的直接子节点。您可以阅读 XPath 的文档来了解更多命令。


XPath 返回节点的集合,因此我总是查询第一个元素[0](假设文档中只有一个这样的元素)


查看完整回答
反对 回复 2023-10-04
  • 1 回答
  • 0 关注
  • 70 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信