2012-02-06 56 views
3

的屬性值我有以下XML結構:PHP:獲取XML

<stores> 
    <store> 
     <name></name> 
     <address></address> 
     <custom-attributes> 
      <custom-attribute attribute-id="country">Deutschland</custom-attribute> 
      <custom-attribute attribute-id="displayWeb">false</custom-attribute> 
     </custom-attributes> 
    </store> 
</stores> 

我怎樣才能獲得 「displayWeb」 的價值?

+0

沒有指標分析,我只是想獲得的「假」 – burner007 2012-02-06 14:55:19

回答

1

您可以使用XPath:

stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb'] 
1

我建議PHP's SimpleXML。該網頁有很多用戶提供的用於從分析數據中提取值的示例。

2

這個最好的解決方法是使用PHP DOM,您可以將循環槽各門店:

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

// With use of child elements: 
$storeNodes = $dom->documentElement->childNodes; 

// Or xpath 
$xPath = new DOMXPath($dom); 
$storeNodes = $xPath->query('store/store'); 

// Store nodes now contain DOMElements which are equivalent to this array: 
// 0 => <store><name></name>....</store> 
// 1 => <store><name>Another store not shown in your XML</name>....</store> 

這些用途DOMDocument propertiesDOMElement屬性childNodesDOMXPath。與xPath

foreach($storeNodes as $node){ 
    // $node should be DOMElement 
    // of course you can use xPath instead of getAttributesbyTagName, but this is 
    // more effective 
    $domAttrs = $node->getAttributesByTagName('custom-attribute'); 
    $attributes = array(); 
    foreach($domAttrs as $domAttr){ 
    $attributes[ $domAttr->getAttribute('attribute-id')] = $domAttr->nodeValue; 
    } 
    // $attributes = array('country' => 'Deutschland', 'displayWeb' => 'false'); 
} 

或者選擇屬性直接:一旦你擁有所有的商店,你可以重複使用foreach循環通過他們,並得到或者所有元素,並將它們存儲到關聯數組getElementsByTagName

// Inside foreach($storeNodes as $node) loop 
$yourAttribute = $xPath->query("custom-attribute[@attribute-id='displayWeb']", $node) 
    ->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag 

或者當您只需從整份文件中選擇一個值(如Kirill Polishchuk建議的):

$yourAttribute = $xPath->query("stores/store/custom-attributes/custom-attribute[@attribute-id='displayWeb']") 
    ->item(0)->nodeValue; // Warning will cause fatal error when missing desired tag 

仔細研究手冊以瞭解什麼時候返回什麼類型,以及哪些屬性包含哪些內容。