2012-04-19 24 views
3

我正在嘗試訪問xml元素的文本值。我正在使用SimpleXMLElement。我必須失去一些明顯的東西。使用SimpleXMLElement獲取元素內部文本

<h:html xmlns:jr="http://openrosa.org/javarosa" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ex="http://www.w3.org/2001/xml-events" xmlns:h="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/2002/xforms"> 
    <h:head> 
    <h:title>NewForm</h:title>  
    </h:head> 
</h:html> 

$xml = new SimpleXMLElement($resp); 
$xml->registerXPathNamespace('h', 'http://www.w3.org/1999/xhtml'); 
// I have tried with and without the namespace (it doesn't seem to make a difference) 

$result = $xml->xpath('//h:title'); 
debug($result); 

運行上面的代碼給我:

array (
    0 => 
    SimpleXMLElement::__set_state(array(
    0 => 'NewForm', 
)), 
) 

看起來很簡單。我有困難得到

我已經試過

$result[0]$result[0]->{0}$result[0][0]的 'NewForm' 的值。

迭代通過$result[0]的孩子。

有人請幫助指導我在正確的方向,所以我可以從標題元素的文本?

+1

你使用會工作的XML的例子很有幫助。並把它與你想要從中解脫出來。 – salathe 2012-04-19 17:51:37

+1

也可以使用'print_r()'而不是'debug()',因爲這看起來是自定義輸出(CakePHP?)。 – 2012-04-19 18:22:37

+0

還請參閱:[訪問SimpleXMLElement對象的某些屬性](http://stackoverflow.com/q/9691847/367456) – hakre 2013-06-24 03:13:21

回答

10

這爲我工作與你的例子:

echo (string)$result[0]; 
1

嘗試強制轉換爲字符串數組中選擇項目後:

[...] 
$result = $xml->xpath('//h:title'); 
echo current($result); 
相關問題