douyi0902 2011-05-30 15:12
浏览 159

PHP XPath。 如何使用html标签返回字符串?

<?php
    libxml_use_internal_errors(true);
    $html = '
<html>
<body>
    <div>
        Message <b>bold</b>, <s>strike</s>
    </div>
    <div>
        <span class="how">
            <a href="link" title="text">Link</a>, <b> BOLD </b>
        </span>
    </div>
</body>
</html>
    ';
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->strictErrorChecking = false;
    $dom->recover = true;
    $dom->loadHTML($html);

    $xpath = new DOMXPath($dom);
    $messages = $xpath->query("//div");
    foreach($messages as $message)
    {
        echo $message->nodeValue;
    }

This code returns "Message bold, strike Link, BOLD " without html tags...

I want to output the following code:

Message <b>bold</b>, <s>strike</s>

<span class="how">
     <a href="link" title="text">Link</a>, <b> BOLD </b>
</span>

Can you help me?

  • 写回答

2条回答 默认 最新

  • dousheyan0375 2011-05-30 15:27
    关注

    I can do it using SimpleXML really quickly (if it's okay for you to switch from DOMDocument and DOMXPath, probably you will go with my solution):

    $html = '
    <html>
    <body>
        <div>
            Message <b>bold</b>, <s>strike</s>
        </div>
        <div>
            <span class="how">
                <a href="link" title="text">Link</a>, <b> BOLD </b>
            </span>
        </div>
    </body>
    </html>
        ';
        $xml = simplexml_load_string($html);
        $arr = $xml->xpath('//div/*');
        foreach ($arr as $x) {
          echo $x->asXML();
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看