【问题标题】:how to convert object(SimpleXMLElement) to string如何将对象(SimpleXMLElement)转换为字符串
【发布时间】:2011-07-16 05:36:12
【问题描述】:

我正在使用 xpath 解析网页中的文本,但它以对象的形式返回它,我如何将它作为字符串返回。

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']");

$username 数组的 var_dump:

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

【问题讨论】:

    标签: php parsing dom xpath


    【解决方案1】:
    list(, $node) = $username;
    
    var_dump($node);
    // object(SimpleXMLElement)#3 (1) { [0]=> string(11) "bubblebubble1210" }
    

    CodePad.

    【讨论】:

    • 我使用了那个代码,它返回了这个字符串(1)“r”,但它不应该返回更多的字符吗?
    • 是的,您是否不小心对结果字符串执行了foreach()(或下标)?
    • 我将如何使用这些代码来解析外部 html 页面而不是字符串
    • @jennifer 你可以使用simplexml_load_file()
    【解决方案2】:

    您可以使用$username->asXML(); 获取该特定 SimpleXMLElement 对象的完整字符串。

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2018-07-19
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多