Reading XML data in PHP, simple

感情迁移 提交于 2020-01-15 06:15:05

问题


<?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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!