Parsing XML using PHP

后端 未结 8 2195
日久生厌
日久生厌 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);
    

提交回复
热议问题