2017-09-26 51 views
2

我想用xpath檢查元素是否出現過多次。xpath - 檢查元素是否不止一次出現

XML:

<XML> 
    <containers> 
     <container id="1"> 
     </container> 
     <container id="2"> 
     </container> 
    </containers> 
</XML> 

我用下面簡單的XPath表達式

$xml->xpath('/XML/containers/container'); 

我試了一下:

Element='<container id="1"> 
     </container>' 
Element='<container id="2"> 
     </container>' 

但作爲一個結果,我想是這樣的數組就像

$containers = array('container', 'container'); 

我該如何歸檔?

+0

在XPath - 你可以使用'計數(/ XML /瓶/箱)',但不幸的是SimpleXML的不支持這種類型的表達(AFAIK) –

回答

2

你不需要一個數組來檢查匹配的數量。中的XPath的只是count()結果,會給你你的電話號碼:

$a = '<XML> 
<containers> 
    <container id="1"> 
    </container> 
    <container id="2"> 
    </container> 
</containers> 
</XML>'; 
$xml = simplexml_load_string($a); 
$containers = $xml->xpath('/XML/containers/container'); 
$totalContainers = count($containers); // 2 

Demo