读取PHP中的XML数据非常简单 [英] Reading XML data in PHP, simple

查看:133
本文介绍了读取PHP中的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>

我怎么读?

因此,我可以像输出内容类别,名称和描述的php循环一样?

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 . " -- ";
    }


推荐答案

category 是属性(不是标签)。请参阅 XML Wikipedia 。要通过 DOMElement 获得它,请使用 getAttribute() Docs

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"), ' -- ';
}

这篇关于读取PHP中的XML数据非常简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆