加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 简单的XML元素:抓住节点内的href

发布时间:2020-12-13 17:00:56 所属栏目:PHP教程 来源:网络整理
导读:我试图解析xml文件中的不同链接.我阅读了文档以及我发现的有关解析xml文件的每篇文章,但我找不到像我想要的那样访问节点的方法.例如: link rel="self" type="text/html" title="title0" length="8359" href="http://example0.com"/link rel="alternate" typ
我试图解析xml文件中的不同链接.我阅读了文档以及我发现的有关解析xml文件的每篇文章,但我找不到像我想要的那样访问节点的方法.例如:

<link rel="self" type="text/html" title="title0" length="8359" href="http://example0.com"/>
<link rel="alternate" type="text/html" title="title1" length="8359" href="http://example3.com"/>
<link rel="related" type="text/html" title="title2" length="8359" href="http://example4.com"/>
<link rel="related" type="text/html" title="title3" length="8359" href="http://example4.com"/>
<link rel="related" type="text/html" title="title4" length="8359" href="http://example5.com"/>
<link rel="related" type="text/html" title="title5" length="8359" href="http://example5.com"/>

我该如何访问:

>具有rel =“self”(返回String)的链接的href.
>具有rel =“alternate”(返回String)的链接的href.
>具有rel =“related”(返回数组)的链接的href.

使用SimpleXML:

$xml=simplexml_load_file('url_to_xml') or die('Error: Cannot create object');

解决方法

该问题通常可以说为“如何根据其他属性之一的值访问XML元素的属性”.有两种基本方法:迭代所有候选元素,并检查属性值;或使用XPath搜索文档.

找到匹配的元素后,您需要访问该属性,在SimpleXML中,这意味着知道两种语法:

> $something [‘bar’]从表示元素的对象(例如< foo>)到表示其属性之一的对象(例如bar =“…”)
>(string)$something将变量强制转换为字符串,对于SimpleXML,它为您提供元素或属性的完整字符串内容

使用SimpleXML使用迭代很简单,因为你可以使用foreach,如果应该是一个相当直观的方式.假设$xml已经指向< link>的父元素内容:

foreach ( $xml->link as $link ) {
    if ( $link['rel'] == 'self' ) {
        // Found <link rel="self">
        // assign to variable,return from function,etc
        // To access the attribute,we use $link['href']
        // To get the text content of the selected node,//   we cast to string with (string)$link['href']
        $self_link = (string)$link['href'];
    }
}

使用XPath,您可以使用紧凑表达式在整个文档中搜索具有特定名称和属性值的元素:

> // foo在文档中的任何位置搜索名为< foo>的所有元素
> [bar]表示“其子元素名为”bar“
> [@bar]意思是“它有一个名为”bar“的属性,这就是我们想要的
> [@ bar =“baz”]表示“bar”属性的值必须为“baz”

所以在我们的例子中,// link [@ rel =“self”].

在SimpleXML中,您可以在任何节点上调用 – > xpath(),并获取零个或多个对象的数组.然后,您将要遍历这些,提取适当的值:

$xpath_results = $xml->xpath('//link[@rel="self"]');
foreach ( $xpath_results as $node ) {
     // Again,we have a SimpleXMLElement object,and want 
     //    the string content of the 'href' attribute:
     $self_link = (string)$node['href'];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读