这
<?php
$xmlstr = '<?xml version="1.0" standalone="yes"?>
<table count="" time="0.010006904602051">
<item>
<id>607</id>
<name>MSPOT6071</name>
<description>Hip Hop / Raps</description>
<type>3</type>
<radio_folder_id/>
<albumart>
http://cdn.7static.com/static/img/sleeveart/00/009/560/0000956027_175.jpg
</albumart>
<albumart_300>
http://cdn.7static.com/static/img/sleeveart/00/009/560/0000956027_350.jpg
</albumart_300>
<albumart_500>
http://cdn.7static.com/static/img/sleeveart/00/009/560/0000956027_500.jpg
</albumart_500>
</item>
<item>
<id>48542614</id>
<name>US Pop - TESTB</name>
<description>Blues</description>
<type>3</type>
<radio_folder_id/>
</item>
</table>';
$xml = new SimpleXMLElement($xmlstr);
foreach($xml->item as $item)
{
echo $item->name."<br>";
}
echo $xml->item[0]->name;
echo '<pre>';
print_r($xml);
echo '</pre>';
?>
将您的 XML 字符串分配给变量 $xmlstr,这样您就不会遇到不完整的 XML 文档错误,请确保您在 XML 文档的顶部包含以下内容。
<?xml version="1.0" standalone="yes"?>
然后通过将 XML 字符串 $xmlstr 传递给 SimpleXML 来使用内置的 SimpleXML 类:
$xml = new SimpleXMLElement($xmlstr);
现在,您可以使用 SimpleXML 类的属性和方法将 XML 文件作为 PHP 对象访问。在本例中,我们遍历 XML 文档中的“项目”并打印出“名称”元素:
foreach($xml->item as $item)
{
echo $item->name."<br>";
}
我还包含访问第一个 item 元素的代码:
echo $xml->item[0]->name;
以及一些调试代码在 SimpleXML 对象中查看 XML 文档:
echo '<pre>';
print_r($xml);
echo '</pre>';
您可以通过名称访问密钥或在本例中为对象属性。因此,在您的 foreach 循环中,您可能会这样做:
if($item->name)
{
echo $item->name;
}
或者
if($item->description)
{
echo $item->description;
}
愿原力与你同在。