从XML中提取值

时间:2016-08-15 12:49:09

标签: php xml

我只是从XML中提取数据时遇到问题。

内容如下:

  <entry>
    <id>tag:blogger.com,1999:blog-227841964192642355.post-8872593151327492602</id>
    <published>2016-08-15T01:56:00.001-07:00</published>
    <updated>2016-08-15T01:56:36.304-07:00</updated>
    <title type='text'>Podaj tytuł wpisu spintax</title>
    <content type='html'>Treść wpisu spintax </content>
    <link rel='replies' type='application/atom+xml' href='http://ecookingwithme.blogspot.com/feeds/8872593151327492602/comments/default' title='Komentarze do posta' />
    <link rel='replies' type='text/html' href='http://ecookingwithme.blogspot.com/2016/08/podaj-tytu-wpisu-spintax.html#comment-form' title='Komentarze (0)' />
    <link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/227841964192642355/posts/default/8872593151327492602' />
    <link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/227841964192642355/posts/default/8872593151327492602' />
    <link rel='alternate' type='text/html' href='I NEED THIS LINK' title='Podaj tytuł wpisu  spintax' />
    <author>
      <name>NAMEa</name>
      <uri>link here</uri>
      <email>noreply@blogger.com</email>
      <gd:image rel='link here' width='16' height='16' src='link here' />
    </author>
    <thr:total>0</thr:total>
  </entry>

何从<link rel='alternate' type='text/html' href='I NEED THIS LINK' title='Podaj tytuł wpisu spintax' />提取数据  ?

我不知道如何提取这个,我可以轻松提取标题,但我不知道如何使用LINK替代,同样感谢您的建议。

以下是我写的内容:

$file = "http://ecookingwithme.blogspot.com/atom.xml";
$xml = simplexml_load_file($file);
echo $xml->entry->title;

我也尝试过:

$file = "http://ecookingwithme.blogspot.com/atom.xml";
$xml = simplexml_load_file($file);

foreach ( $xml->entry as $foo ) {
    foreach ( $foo->link as $link ) {
        $type = (string) $link->attributes()->{'rel'};
        if ( $type == 'rel' ) {
            echo (string) $link->attributes()->{'href'};
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您已经在entry元素中,因此只需遍历link即可获得href

$sxml = new simplexmlelement($xml);
foreach($sxml->link as $link) {
     if($link['rel'] == 'alternate') {
          echo $link['href'];
     }
}

演示:https://eval.in/622605

答案 1 :(得分:0)

不使用simple_xml,而是使用常规DOMDocument,您可以在几行代码中执行此操作

$file='http://ecookingwithme.blogspot.com/atom.xml';

$dom=new DOMDocument;
$dom->load( $file );

$col=$dom->getElementsByTagName('link');
foreach( $col as $node ) echo $node->getAttribute('href').'<br />';