我尝试获取xml的元素名称。我使用getName()函数。但我不知道为什么它总是出错,它在那个页面上出错。
$xml=filePath::$xml; //guide to the xml file
//use simple xml to get the attributes
$xmldoc=simplexml_load_file($xml);
//get the children
foreach($xmldoc->children() as $child) {
foreach($child->attributes() as $a=>$b) {
echo $b;//this statement works correctly
}
echo $child->getName();//this statement does not work, and it leads to the error.
}
为什么?
xml文件如: 根 集合id =“new1” 斜线收集 集合id =“new2” 斜线收集 削减根
正确的输出应该是:new1 collection new2 collection。但是“收藏”不能打印出来。
答案 0 :(得分:1)
请检查以下内容,我为您提供了两个关于如何从本地和远程XML加载,获取和打印数据的示例,也许您忘记了一些事情。
如果100%正确,也可以检查XML文档语法。
您可以使用此工具验证XML:
http://www.w3schools.com/xml/xml_validator.asp
加载本地XML,获取并打印数据
<?php
// xml example with namespaces
$xml = '<market
xmlns:m="http://mymarket.com/">
<m:fruit>
<m:type>
<m:name from="US">Apples</m:name>
<m:name>Bananas</m:name>
</m:type>
<m:sell>
<m:date>2012-06-24</m:date>
</m:sell>
</m:fruit>
</market>';
// load the xml
$elems = simplexml_load_string($xml);
// evaluate if not null
if($elems != null){
// declare the namespaces
$ns = array(
'm' => "http://mymarket.com/"
);
// for each td inside tr
foreach ($elems->children($ns['m'])->fruit->type->name as $item) {
echo $item->attributes()->from;
echo ',';
echo $item;
}
// get just an element without using loop
echo ','.$elems->children($ns['m'])->fruit->sell->date;
// final output is: US,Apples,Bananas,2012-06-24
}
?>
加载远程XML,获取并打印数据
<?php
$url = "http://www.mymarket.com/products.xml";
// evaluate if not null
if(getXml($url) != null){
// declare the namespaces
$ns = array(
'm' => "http://mymarket.com/"
);
// for each td inside tr
foreach ($elems->children($ns['m'])->fruit->type->name as $item) {
echo $item->attributes()->from;
echo ',';
echo $item;
}
// get just an element without using loop
echo ','.$elems->children($ns['m'])->fruit->sell->date;
// final output is: US,Apples,Bananas,2012-06-24
}
function getXml($url)
{
$xml = @file_get_contents($url);
// If page not found and server has a 404 error redirection, use strpos to look through the $xml
if($xml == false || strpos($xml,'404') == true){
return null;
}
else{
$elems = simplexml_load_string($xml);
return $elems;
}
}
?>
答案 1 :(得分:0)
您确定xml文档有效吗?
脚本是否已超越
if($xmldoc!=null)
{
它可能声明$ xmldoc为null,因为该文档无效。