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 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题