2017-04-12 72 views
0

我有類似下面的文本的XML文件:PHP和XPath查詢

<?xml version="1.0" standalone="yes"?> 
<Calendar xmlns="urn:AvmInterchangeSchema-Calendario-1.0"> 
    <Date> 
    <Day>12/04/2017</Day> 
    <TypesDay> 
     <Type>Test 1</Type> 
     <Type>Test 2</Type> 
     <Type>Test 3</Type> 
    </TypesDay> 
    </Date> 
</Calendar> 

,我使用這個XPath來選擇的節點:

$xml = simplexml_load_file("file.xml"); 
$response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]'); 

我怎樣才能把「TypesDay 「條目是否滿足?

我希望不要造成重複...我要瘋了幾個小時,它肯定是一件小事。

+1

https://eval.in/775280 – splash58

+0

感謝@ splash58,也是你的答案是非常有用的 –

回答

2

有幾種方法可以做到這一點。

$xml->registerXPathNamespace('x', 'urn:AvmInterchangeSchema-Calendario-1.0'); 

我假設與價值12/04/2017節點名稱可以改變:首先,要註冊的命名空間。

首先

找到一個名爲TypesDay命名的命名空間x父節點具有價值的子節點12/04/2017

$response = $xml->xpath('//*[*[text()="'.date("d/m/Y").'"]]/x:TypesDay'); 

內部節點找到一個名爲節點TypesDay命名空間內x是節點的兄弟與價值12/04/2017

$response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]/following-sibling::x:TypesDay'); 

兩個結果是:

array(1) { 
    [0]=> 
    object(SimpleXMLElement)#2 (1) { 
    ["Type"]=> 
    array(3) { 
     [0]=> 
     string(6) "Test 1" 
     [1]=> 
     string(6) "Test 2" 
     [2]=> 
     string(6) "Test 3" 
    } 
    } 
} 

畢竟,如果你只想要的條目,只需添加一個新的水平/x:Type

$response = $xml->xpath('//*[*[text()="'.date("d/m/Y").'"]]/x:TypesDay/x:Type'); 

或者:

$response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]/following-sibling::x:TypesDay/x:Type'); 

結果:

array(3) { 
    [0]=> 
    object(SimpleXMLElement)#3 (1) { 
    [0]=> 
    string(6) "Test 1" 
    } 
    [1]=> 
    object(SimpleXMLElement)#4 (1) { 
    [0]=> 
    string(6) "Test 2" 
    } 
    [2]=> 
    object(SimpleXMLElement)#5 (1) { 
    [0]=> 
    string(6) "Test 3" 
    } 
} 
+0

感謝您的答覆,我也沒有登記的命名空間,這是所有有機會看到。 感謝您的解釋,我也可以檢查文件中的TypesDay實際存在。 非常感謝。 –