2011-03-16 118 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