我有一个xml数据,看起来像这样
<channel>
<title>-----</title>
<link>------</link>
<description>---</description>
<lastBuildDate>Tue, 27 Sep 2011 16:37:01 +0000</lastBuildDate>
<language>en</language>
<generator>-------</generator>
<item>
<title>-----</title>
<link>-------</link>
<comments>------</comments>
<pubDate>Tue, 27 Sep 2011 16:37:01 +0000</pubDate>
<category>-----</category>
</item>
<item>
<title>-----</title>
<link>-------</link>
<comments>------</comments>
<pubDate>Tue, 27 Sep 2011 </pubDate>
<category>-----</category>
</item>
<item>
<title>-----</title>
<link>-------</link>
<comments>------</comments>
<pubDate>Wed, 28 Sep 2011 16:37:01 +0000</pubDate>
<category>-----</category>
</item>
</channel>
从这里我需要检索用户的所有现有XML标签,如频道、标题、链接、项目等,包括它们的子标签。我的意思是,在XML文件中的所有现有标签,我需要帮助如何使用php,我使用了DOM和简单的XML对象,但我只能获得特定标签中的值,如果我知道我需要的标签名称。
但我实际上需要处理许多xml文件,我不知道特定xml的结构和标签是什么,因此我需要获得现有的标签名称,以便我可以将它们显示给用户,以选择他需要的标签……
我需要使用php来做这个的建议。
提前谢谢。
发布于 2011-10-03 15:26:43
这是我的尝试:
$doc = new DOMDocument();
$doc->loadXML( $yourXmlString ); // or:
$doc->load( $yourXmlUrl );
$xpath = new DOMXpath( $doc );
$nodes = $xpath->query( '//*' );
$nodeNames = array();
foreach( $nodes as $node )
{
$nodeNames[ $node->nodeName ] = $node->nodeName;
}
var_dump( $nodeNames );
我希望我能让xpath
表达式更高效一些,但是我想不出任何东西。这就是为什么我不断地重写$nodeNames
的密钥。
想想看:也许我误解了您的问题,您根本不想要唯一的元素名称,而是想要字面上的所有元素。如果是这样的话:你想要什么样的?作为字符串?包括他们的完整路径?
发布于 2011-10-03 15:10:03
下面是一个简单的示例,演示了如何使用http://php.net/manual/en/simplexml.examples-basic.php中的PHP库SimpleXML
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Get attributes as element indices
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>
https://stackoverflow.com/questions/7636815
复制相似问题