在PHP

2010-09-02 37 views
1

解析使用XPath的XML考慮下面的代碼:在PHP

$dom = new DOMDocument(); 
$dom->loadXML($file); 

$xmlPath = new DOMXPath($dom); 
$arrNodes = $xmlPath->query('*/item'); 
foreach($arrNodes as $item){ 
//missing code 
} 

的$文件是一個XML,並且每個項目都有一個標題和描述。 如何顯示它們(標題和說明)?

$file = "<item> 
    <title>test_title</title> 
    <desc>test</desc> 
</item>"; 

回答

2

如果你的項目是這樣的:

<item> 
    <title>foo</title> 
    <description>frob</description>  
</item> 

你可以使用getElementsByTagName()nodeValue

foreach($arrNodes as $item){ 
    print $item->getElementsByTagName('title')->item(0)->nodeValue; 
} 

titledescription屬性?例如,沒有一個項目像這樣:

<item title="foo" description="frob" /> 

如果是這樣,你可以只使用getAttribute()

... 
foreach($arrNodes as $item){ 
    print $item->getAttribute('title'); 
} 
+0

他們是節點。 – danidacar 2010-09-02 18:31:22

6

我建議使用PHP的simplexml,與,你仍然可以得到xpath的功能,但更簡單的方法,例如,你會像這樣訪問屬性:

$name = $item['name']; 

下面是一個例子:

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<xml> 
    <items> 
     <item title="Hello World" description="Hellowing the world.." /> 
     <item title="Hello People" description="greeting people.." /> 
    </items> 
</xml> 

do.p馬力:

<?php 
$xml_str = file_get_contents('xmlfile.xml'); 
$xml = new SimpleXMLElement($xml_str); 
$items = $xml->xpath('*/item'); 

foreach($items as $item) { 
    echo $item['title'], ': ', $item['description'], "\n"; 
} 
+0

好吧,但xpath是有限的嗎? – danidacar 2010-09-02 18:25:01

+0

我編輯添加一個例子,如果你想檢查和測試。 – aularon 2010-09-02 18:30:09

+0

@daniphp,你的意思是說,你是在問一般的xpath查詢能力還是關於simplexml的限制? – aularon 2010-09-02 18:34:59

0

正確的XPath表達式應該是:

/*/item/title | /*/item/desc 

或者

/*/item/*[self::title or self::desc] 

這是評估te按照文檔順序設置爲titledesc元素的節點