2011-02-26 37 views
2

使用PHP的simplexml_load_string如何獲取標籤的值是否將特定屬性設置爲特定值?PHP:simplexml_load_string

+4

可能重複的[PHP:解析用SimpleXML表結構](http://stackoverflow.com/questions/1730428/php-parsing-table-structure-with-simplexml) – Gordon 2011-02-26 11:17:18

回答

1

加載XML數據後,您應該可以使用SimpleXMLElement::xpath方法對其執行XPath查詢以查找特定元素。


例如,考慮到你有一個XML字符串,並加載它是這樣的:

$xmlString = <<<TEST 
<root> 
    <elt plop="test">aaa</elt> 
    <elt plop="huhu">bbb</elt> 
</root> 
TEST; 

$xml = simplexml_load_string($xmlString); 

你可以使用下面的代碼部分找到<elt>標記,其中plop屬性的值爲huhu

$elt = $xml->xpath('//elt[@plop="huhu"]'); 
var_dump($elt); 

而且你會得到這樣的輸出:

array 
    0 => 
    object(SimpleXMLElement)[2] 
     public '@attributes' => 
     array 
      'plop' => string 'huhu' (length=4) 
     string 'bbb' (length=3) 
0
<?php 
// heredoc use 
    $string = <<<XML 
    <?xml version='1.0'?> 
    <document> 
    <title>Forty What?</title> 
    <from>Joe</from> 
    <to>Jane</to> 
    <body> 
     I know that's the answer -- but what's the question? 
    </body> 
    </document> 
    XML; 

    $xml = simplexml_load_string($string); 
    echo $xml->title; // you can get "Forty What?" value`enter code here` 
    ?>