Parsing XML using PHP

后端 未结 8 2188
日久生厌
日久生厌 2020-12-12 02:16

I\'ve consistently had an issue with parsing XML with PHP and not really found \"the right way\" or at least a standardised way of parsing XML files.

Firstly i\'m tr

相关标签:
8条回答
  • 2020-12-12 02:49

    You can use SimpleXML as suggested by the other posters, but you need to use the children() and attributes() functions so you can deal with the different namespaces

    Example (untested):

    $feed = file_get_contents('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
    $xml = new SimpleXMLElement($feed);
    foreach ($xml->channel->item as $item) {
        foreach ($item->children('http://search.yahoo.com/mrss' as $media_element) {
            var_dump($media_element);
        }
    }
    

    Alternatively, you can use XPath (again, untested):

    $feed = file_get_contents('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
    $xml = new SimpleXMLElement($feed);
    $xml->registerXPathNamespace('media', 'http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
    $images = $xml->xpath('/rss/channel/item/media:content@url');
    var_dump($images);
    
    0 讨论(0)
  • 2020-12-12 02:50

    You would want something like this:

    'content' => $node->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content')->item(0)->getAttribute('url');
    'thumbnail' => $node->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')->item(0)->getAttribute('url');
    

    I believe that will work, it's been a while since I've done anything like this.

    0 讨论(0)
提交回复
热议问题