How to extract the content of <uri></uri> in a XML document?

那年仲夏 提交于 2019-12-08 13:54:07

问题


I have a document that it's structure is like below.
There are a lot of <entry>. My question is how can I output the <uri> of each entry? And another question, how can I output only the USERNAME?

This is the file I want to get the usernames http://search.twitter.com/search.atom?q=yankees

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:google="http://base.google.com/ns/1.0" xml:lang="en-US" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns="http://www.w3.org/2005/Atom" xmlns:twitter="http://api.twitter.com/" xmlns:georss="http://www.georss.org/georss">

<entry>
  <author>
    <name></name>
      <uri>http://twitter.com/USERNAME</uri>
  </author>
</entry>


回答1:


<?php
$xml = new DOMDocument;

// link to ur file
$xml->load('');    

foreach ($xml->getElementsByTagName('entry') as $product ) 
{
    $append = array();

    foreach($product->getElementsByTagName('uri') as $name ) {
        // Stick $name onto the array
        $append[] = $name;
    }
}

$result = $xml->saveXML();
print_r(str_replace('http://twitter.com/','',$result));
?>



回答2:


You can use Xpath queries http://www.php.net/manual/en/simplexmlelement.xpath.php or http://php.net/manual/en/domxpath.query.php




回答3:


You should use SimpleXML some kind of a loop which goes trough all the s. (foreach($xml->entry as $entry) loop should work fine, I think.)

And for the second: if it is always http://twitter.com/USERNAME, simply count the prefix's length than use a substr.

Resources to use: substr, SimpleXML, SimpleXML



来源:https://stackoverflow.com/questions/9199041/how-to-extract-the-content-of-uri-uri-in-a-xml-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!