简体   繁体   中英

How can I retrieve specific XML tag names?

The feed above returns an XML document. I can successfully retrieve tag names like title,description and link using these codes

    $xml = file_get_contents($feed_url);
    $xml = trim($xml);
    $xmlObject = new SimpleXmlElement($xml);   


    foreach ($xmlObject->channel->item as $item) {
      $title = strip_tags($item->title);
      $description = strip_tags($item->description);

    }

How can I get <a10:updated> ?

<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
    <title>title/title>
    <link>link</link>
    <description>news</description>
    <item>
    <guid isPermaLink="true">link</guid>
    <link>link</link>
    <title>Tiele</title>
    <description>Descr</description>
    <enclosure url="image" type="image/jpeg"/>
    <a10:updated>2017-05-07T09:14:00+03:00</a10:updated>
    </item>
    </channel>
</rss>

Here we are using DOMDocument for extracting data from a tag.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$xml='<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
        <title>title</title>
        <link>link</link>
        <description>news</description>
        <item>
            <guid isPermaLink="true">link</guid>
            <link>link</link>
            <title>Tiele</title>
            <description>Descr</description>
            <enclosure url="image" type="image/jpeg"/>
            <a10:updated>2017-05-07T09:14:00+03:00</a10:updated>
        </item>
    </channel>
</rss>';

$xmlObject = new DOMDocument();
$xmlObject->loadXML($xml);
$result=$xmlObject->getElementsByTagNameNS("http://www.w3.org/2005/Atom", "*");
print_r($result->item(0)->textContent);

Output: 2017-05-07T09:14:00+03:00

You're looking at a different XML namespace there. You can use curly brackets to access it:

 $a10 = $item->{'a10:updated'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM