2013-02-01 82 views
2

我想過濾一個xml提要,所以我只用正確的語言導入數據。php簡單的xml篩選器屬性

結構爲:

<profile_lang lang="en"> 
<description>English description</description> 
</profile_lang> 
<profile_lang lang="fr"> 
<description>French</description> 
</profile_lang> 
<profile_lang lang="nl"> 
<description>Dutch text</description> 
</profile_lang> 

我應該需要做的僅導入荷蘭(LANG = 「NL」)的描述?

回答

1

XPath是靶向/過濾的好方法/在一個XML結構

$xml = '<root><profile_lang lang="en"><description>English description</description></profile_lang><profile_lang lang="fr"><description>French</description></profile_lang><profile_lang lang="nl"><description>Dutch text</description></profile_lang></root>'; 
$simple = simplexml_load_string($xml); 
$description = $simple->xpath('/root/profile_lang[@lang="nl"]/description'); 
echo $description[0]; // Dutch text 

你可以拿出你自己的路徑結構搜索特定元素,以滿足您的需求

/root/profile_lang[@lang="nl"]/description 
//profile_lang[@lang="nl"]/description 
//profile_lang[@lang="nl"] 
//description[../@lang="nl"] 
1

嘗試

$xml = <<<XML 
<profile_lang lang="en"> 
<description>English description</description> 
</profile_lang> 
<profile_lang lang="fr"> 
<description>French</description> 
</profile_lang> 
<profile_lang lang="nl"> 
<description>Dutch text</description> 
</profile_lang> 
XML; 

$xml = new SimpleXMLElement($xml); 
$nodes = $xml->xpath('//*[@lang="en"]'); 

echo 'Found ', count($nodes), ' node(s) with lang "en".';