2011-12-12 78 views
2
<?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读取XML数据,简单

因此,我可以像一个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 . " -- "; 
    } 
+1

'category'是一个属性(不是标签)。请参阅XML。要通过'DOMElement'获取它,请使用['getAttribute()'](http://www.php.net/manual/en/domelement.getattribute.php)。 – hakre

+0

@hakre谢谢你的工作。请将它写为答案 – Karem

+0

当然,我还添加了一些示例代码;)。 – hakre

回答

2

category是属性(不是标签)。见XMLWikipedia。要通过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"), ' -- '; 
} 
+0

真的很棒的帖子..谢谢 –

2

我建议PHP的simplexml_load_file()

$xml = simplexml_load_file($xmlFile); 
foreach ($xml->items->item as $item) { 
    echo $item['category'] . ", " . $item['name'] . ", " . $item['description'] . "\n"; 
} 

更新时,错过了额外的标签。

+0

好主意,执行不力。 [它不起作用](http://codepad.viper-7.com/LYlBIT)。 – nickb

+0

@nickb,谢谢你的发现。 – nachito

+0

+1好得多':)' – nickb

1

这里使用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']; 
}