2012-07-24 86 views
0

我有一個這樣的XML:XML檢索具有屬性的項目?

<DescriptionsComplementaires> 
    <DetailDescriptionComplementaire lang="fr" libelle="Descriptif" type="16.01.04"> 
     <Description lang="fr" libelle="Tarifs en clair" type="16.02.67">Gratuit</Description> 
    </DetailDescriptionComplementaire> 
    <DetailDescriptionComplementaire lang="fr" libelle="Descriptif" type="16.01.04"> 
     <Description lang="fr" libelle="Présentation, descriptif commercial" type="16.02.30">Chaussure de marche conseillées. De 12h à 14h sur présentation du ticket remis au départ: Apéritif offert par la commune des Haies Assiette dégustation de produits du terroir offerte pas la communauté de communes. Petit marché de producteurs locaux. Animations et stands d'information. Exposition "les 100 paniers du monde" Café et buvette. 
     </Description> 
    </DetailDescriptionComplementaire> 
</DescriptionsComplementaires> 
    ........ 

我怎麼能在PHP中檢索與libelle = 「XXX」 項目?我使用DOMDocument()。

編輯:

$dom = new DOMDocument; 
$dom->load('(629)_ListeOI_fr_20120720_043502.xml'); 
$attr = "Présentation, descriptif court"; 
$query = "//*[@libelle='{$attr}']"; 
$xpath = new DOMXPath($dom); 
$entries = $xpath->query($query); 

foreach ($entries as $entry) { 
    //i don't know what to do here for display items 
} 

回答

0

的DomDocument的XPath

$dom = new DOMDocument; 
$dom->loadXML($xml_string); 
$attr = "Descriptif"; 
$query = "//*[@libelle='{$attr}']"; 
$xpath = new DOMXPath($dom); 
$entries = $xpath->query($query); 

遍歷結果:http://www.php.net/manual/en/domxpath.query.php

+0

你能幫我一個例子嗎?我需要在我的XML中檢索所有「Présentation,descriptif commercial」。 – 2012-07-24 12:43:18

+0

我有一個foreach:foreach($ entries爲$ entry){},如何顯示$條目的所有值? – 2012-07-24 12:55:49

+0

閱讀我已包含的文檔 – ajreal 2012-07-24 13:27:42

0

使用PHP的SimpleXML :: XPath的http://php.net/manual/en/simplexmlelement.xpath.php,而不是你的方法。您的代碼將被簡化,會是這個樣子:

$xml = new SimpleXMLElement($xmlStr); 
$res = $xml->xpath("//*[@libelle=XXX]"); 
print_r($res); 
+0

並與我的例子嗎?我需要先用'''$ xmlStr = file_get_contents(「name.xml」)加載一個.xml第一個 – 2012-07-24 12:31:38

+0

加載xml文件'''然後你可以使用about代碼。 – MaX 2012-07-24 12:50:22

+0

也許在回答問題之前測試你的代碼... – 2012-07-24 12:54:33