问题
<?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>
How can i read this?
So i can make like a php loop that outputs the category, name and description for example?
I tried and started out with this:
$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 . " -- ";
}
回答1:
category
is an attribute (not a tag). See XMLWikipedia. To obtain it via the DOMElement
, use getAttribute()Docs:
foreach ($items as $item)
{
$category = $item->getAttribute('category');
echo $category, ' -- ';
}
Same for description
, just change the name of the attribute to obtain:
foreach ($items as $item)
{
echo 'Category: ', $item->getAttribute("category"), "\n",
'Description: ', $item->getAttribute("description"), ' -- ';
}
回答2:
I'd recommend PHP's simplexml_load_file()
$xml = simplexml_load_file($xmlFile);
foreach ($xml->items->item as $item) {
echo $item['category'] . ", " . $item['name'] . ", " . $item['description'] . "\n";
}
UPDATED, missed the extra tag.
回答3:
Here an example using PHP's SimpleXML, specifically the simplexml_load_string function.
$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'];
}
来源:https://stackoverflow.com/questions/8482038/reading-xml-data-in-php-simple