请检查以下内容,我为您提供了两个有关如何从本地和远程 XML 加载、获取和打印数据的示例,也许您忘记了一些事情。
如果 XML 文档语法 100% 正确,您也可以检查它。
您可以使用此工具来验证您的 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;
}
}
?>