dongpu1315 2010-09-27 15:15
浏览 38
已采纳

如何使用PHP DOMDocument获取元素的序列化HTML?

This is my example script:

$html = <<<HTML
<div class="main">
    <div class="text">
    Capture this text 1
    </div>
    <div class="date">
    May 2010
    </div>
</div>
<div class="main">
    <div class="text">
    Capture this text 2
    </div>
    <div class="date">
    June 2010
    </div>
</div>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);


$tags = $xpath->query('//div[@class="main"]');
foreach ($tags as $tag) {
    print_r($tag->nodeValue."
");
}

This will out put:

Capture this text 1 May 2010
Capture this text 2 June 2010 

But I need it output:

<div class="text">
Capture this text 2
</div>
<div class="date">
June 2010
</div>

Or atleast be able to do something like this in my foreach loop:

$text = $tag->query('//div[@class="text"]')->nodeValue;
$date = $tag->query('//div[@class="date"]')->nodeValue;
  • 写回答

2条回答 默认 最新

  • dragon201401 2010-09-27 15:20
    关注

    Well, nodeValue will give you the node's value. You want what's commonly called outerHTML

    echo $dom->saveXml($tag);
    

    will output what you are looking for in an X(HT)ML compliant way.


    As of PHP 5.3.6 you can also pass a node to saveHtml, which wasnt possible previously:

    echo $dom->saveHtml($tag);
    

    The latter will obey HTML4 syntax. Thanks to Artefacto for that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输