[英]Reading XML data in PHP, simple
<?xml version="1.0" encoding="utf-8"?>
<mainXML>
<items>
<item category="Dekorationer" name="Flot væg" description="Meget flot væg. Passer alle stuer." price="149" />
<item category="Fritid" name="Fodbold" description="Meget rund bold. Rørt af messi." price="600" />
</items>
</mainXML>
我该怎么读?
因此,我可以像输出内容类别,名称和描述的php循环一样?
我尝试并以此开始:
$doc = new DOMDocument();
$doc->load( 'ex.xml' );
$items = $doc->getElementsByTagName( "item" );
foreach( $items as $item )
{
$categorys = $item->getElementsByTagName( "category" );
$category = $categorys->item(0)->nodeValue;
echo $category . " -- ";
}
我建议使用PHP的simplexml_load_file()
$xml = simplexml_load_file($xmlFile);
foreach ($xml->items->item as $item) {
echo $item['category'] . ", " . $item['name'] . ", " . $item['description'] . "\n";
}
已更新,错过了多余的标签。
category
是一个属性(不是标签)。 参见XML Wikipedia 。 要通过DOMElement
获得它,请使用getAttribute()
Docs :
foreach ($items as $item)
{
$category = $item->getAttribute('category');
echo $category, ' -- ';
}
与description
相同,只需更改属性名称即可获得:
foreach ($items as $item)
{
echo 'Category: ', $item->getAttribute("category"), "\n",
'Description: ', $item->getAttribute("description"), ' -- ';
}
这是一个使用PHP的SimpleXML(特别是simplexml_load_string函数)的示例。
$xml = '<?xml version="1.0" encoding="utf-8"?>
<mainXML>
<items>
<item category="Dekorationer" name="Flot væg" description="Meget flot væg. Passer alle stuer." price="149" />
<item category="Fritid" name="Fodbold" description="Meget rund bold. Rørt af messi." price="600" />
</items>
</mainXML>';
$xml = simplexml_load_string( $xml);
foreach( $xml->items[0] as $item)
{
$attributes = $item[0]->attributes();
echo 'Category: ' . $attributes['category'] . ', Name: ' . $attributes['name'] . ', Description: ' . $attributes['description'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.