php XMLReader读取xml文件并解析
$xmlData = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.awzsr.com/</loc>
<lastmod>2013-06-13 01:20:01</lastmod>
<changefreq>always</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.awzsr.com/category/</loc>
<lastmod>2013-06-13 01:20:01</lastmod>
<changefreq>always</changefreq>
<priority>0.8</priority>
</url>
</urlset>
XML;
$xml = new XMLReader();
// $url = 'http://www.awzsr.com/baidu_sitemap1.xml';
// $xml->open($url);
$xml->XML($xmlData);
$assoc = xml2assoc($xml);
$xml->close();
function xml2assoc($xml) {
$tree = null;
while($xml->read())
switch ($xml->nodeType) {
case XMLReader::END_ELEMENT: return $tree;
case XMLReader::ELEMENT:
$node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
if($xml->hasAttributes)
while($xml->moveToNextAttribute())
$node['attributes'][$xml->name] = $xml->value;
$tree[] = $node;
break;
case XMLReader::TEXT:
case XMLReader::CDATA:
$tree .= $xml->value;
}
return $tree;
}
查看数据:
echo '<pre>';
print_r($assoc);
echo '</pre>';
|
