2011-03-16 27 views
2

我使用xpath從網頁解析文本,但它將其作爲對象返回,我如何將它作爲字符串返回。如何將對象(SimpleXMLElement)轉換爲字符串

libxml_use_internal_errors(TRUE); 
$dom = new DOMDocument(); 
$dom->loadHTML($source); 
$xml = simplexml_import_dom($dom); 
libxml_use_internal_errors(FALSE); 
$username = $xml->xpath("//span[@class='user']"); 

的var_dump的$用戶名數組:

object(SimpleXMLElement)#3 (2) { ["@attributes"]=> array(1) { ["class"]=> string(4) "user" } [0]=> string(11) "bubblebubble1210" } 

回答

3
list(, $node) = $username; 

var_dump($node); 
// object(SimpleXMLElement)#3 (1) { [0]=> string(11) "bubblebubble1210" } 

$node仍將之上的對象,但你可以(string)顯式轉換或使用echo將隱式轉換它。

CodePad

+0

我用那個代碼,它返回這個字符串(1)「r」,但它不應該返回更多的字符? – jennifer 2011-03-16 00:33:21

+0

是的,你是不是意外地對結果字符串執行'foreach()'(或者下標)? – alex 2011-03-16 00:34:16

+0

我將如何使用這些代碼來解析外部html頁面而不是字符串 – jennifer 2011-03-16 00:38:36