使用PHP解析XML

时间:2009-07-13 20:45:28

标签: php xml parsing domdocument

我一直遇到使用PHP解析XML而不是真正找到“正确方法”或至少是解析XML文件的标准化方法的问题。

首先我想解析一下:

  <item> 
     <title>2884400</title> 
     <description><![CDATA[ ><img width="126" alt="" src="http://userserve-ak.last.fm/serve/126/27319921.jpg" /> ]]></description> 
     <link>http://www.last.fm/music/+noredirect/Beatles/+images/27319921</link> 
     <author>anne710</author> 
     <pubDate>Tue, 21 Apr 2009 16:12:31 +0000</pubDate> 
     <guid>http://www.last.fm/music/+noredirect/Beatles/+images/27319921</guid> 
     <media:content url="http://userserve-ak.last.fm/serve/_/27319921/Beatles+2884400.jpg" fileSize="13065" type="image/jpeg" expression="full"  width="126" height="126" /> 
     <media:thumbnail url="http://userserve-ak.last.fm/serve/126/27319921.jpg" type="image/jpeg" width="126" height="126" /> 
  </item> 

我正在使用此代码:

$doc = new DOMDocument();
$doc->load('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
    $itemRSS = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
        );
    array_push($arrFeeds, $itemRSS);
}

现在我想获得“media:content”和“media:thumbnail”url属性,我该怎么做?现在我认为我应该使用DOMElement :: getAttribute但我还没有设法让它工作:/任何人都可以对此有所了解,并且如果这是解析XML的好方法,还让我知道吗?

此致 沙迪

8 个答案:

答案 0 :(得分:3)

您可以按照其他海报的建议使用SimpleXML,但您需要使用children()和attributes()函数,以便deal with the different namespaces

示例(未经测试):

$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);
    }
}

或者,您可以使用XPath(再次,未经测试):

$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);

答案 1 :(得分:2)

试试这个。它会正常工作。

$doc = new DOMDocument();
$doc->load('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
    $itemRSS = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
        'thumbnail' => $node->getElementsByTagName('thumbnail')->item(0)->getAttribute('url')
    );
    array_push($arrFeeds, $itemRSS);
}

答案 2 :(得分:1)

这就是我最终使用XMLReader完成它的方式:

<?php

define ('XMLFILE', 'http://ws.audioscrobbler.com/2.0/artist/vasco%20rossi/images.rss');
echo "<pre>";

$items = array ();
$i = 0;

$xmlReader = new XMLReader();
$xmlReader->open(XMLFILE, null, LIBXML_NOBLANKS);

$isParserActive = false;
$simpleNodeTypes = array ("title", "description", "media:title", "link", "author", "pubDate", "guid");

while ($xmlReader->read ())
{
    $nodeType = $xmlReader->nodeType;

    // Only deal with Beginning/Ending Tags
    if ($nodeType != XMLReader::ELEMENT && $nodeType != XMLReader::END_ELEMENT) { continue; }
    else if ($xmlReader->name == "item") {
        if (($nodeType == XMLReader::END_ELEMENT) && $isParserActive) { $i++; }
        $isParserActive = ($nodeType != XMLReader::END_ELEMENT);
    }

    if (!$isParserActive || $nodeType == XMLReader::END_ELEMENT) { continue; }

    $name = $xmlReader->name;

    if (in_array ($name, $simpleNodeTypes)) {
        // Skip to the text node
        $xmlReader->read ();
        $items[$i][$name] = $xmlReader->value;
    } else if ($name == "media:thumbnail") {
        $items[$i]['media:thumbnail'] = array (
                "url" => $xmlReader->getAttribute("url"),
                "width" => $xmlReader->getAttribute("width"),
                "height" => $xmlReader->getAttribute("height"),
                "type" => $xmlReader->getAttribute("type")
        );
    } else if ($name == "media:content") {
        $items[$i]['media:content'] = array (
                "url" => $xmlReader->getAttribute("url"),
                "width" => $xmlReader->getAttribute("width"),
                "height" => $xmlReader->getAttribute("height"),
                "filesize" => $xmlReader->getAttribute("fileSize"),
                "expression" => $xmlReader->getAttribute("expression")
        );
    }
}

print_r($items);
echo "</pre>";

?>

答案 3 :(得分:0)

你会想要这样的东西:

'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');

我相信这会奏效,因为我做过这样的事情已经有一段时间了。

答案 4 :(得分:0)

<?php

#Convert the String Into XML
$xml = new SimpleXMLElement($_POST['name']);

#Itterate through the XML for the data 

$values = "VALUES('' , ";
foreach($xml->item as $item)
{
 //you now have access to that aitem
}

?>

答案 5 :(得分:0)

尝试使用SimpleXML:http://us2.php.net/simplexml

答案 6 :(得分:0)

如果Feed缺少Call to a member function getAttribute() on a non-object等条目,您可能会收到错误thumbnail,所以当我喜欢@Helder Robalo的回答时,您应该检查以确保节点存在使用像getAttribute()这样的东西:

<?php

header('Content-type: text/plain; charset=utf-8');

$doc = new DOMDocument();
$doc->load('http://ws.audioscrobbler.com/2.0/artist/beatles/images.rss');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('item') as $node) {
    $itemRSS = array (
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
    );

    if( sizeof($node->getElementsByTagName('thumbnail')->item(0)) > 0 )
    {
        $itemRSS['thumbnail'] = $node->getElementsByTagName('thumbnail')->item(0)->getAttribute('url');
    }
    else
    {
        $itemRSS['thumbnail'] = '';
    }

    array_push($arrFeeds, $itemRSS);
}


print_r($arrFeeds);

答案 7 :(得分:0)

媒体:使用SIMPLE XML实际上很容易获得内容属性

if(!@$x=simplexml_load_file($feed_url)){

}
else
{
  foreach($x->channel->item as $entry)
  {
    $media = $entry->children('http://search.yahoo.com/mrss/')->attributes();
    $url = (string) $media['url'];
  }
}