search

Home  >  Q&A  >  body text

使用PHP XPath采集的时候,如何保留nodeValue里的html符号

代码如下:

$html = <<<EOF
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<p id="content">
  <p>
    <span>
      abcdefghijklmn<br />opqrstuvwxyz
    </span>
  </p>
</p>

</body>
</html>
EOF;
// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query('//*[@id="content"]/p/span');
$content = $elements->item(0)->nodeValue;
echo $content;

内容里的<br />会被去除,使用什么操作比如有没有$e->innerHtml之类的,可以保留html标签。

8.18 更新:

$html = <<<EOF
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<p id="content">
  <p>
    <span class='aaa'>
      abcdefghijklmn<br /><span>opq</span>rstuvwxyz
    </span>
  </p>
</p>

</body>
</html>
EOF;

// create document object model
$dom = new DOMDocument();
// load html into document object model
@$dom->loadHTML($html);
// create domxpath instance
$xPath = new DOMXPath($dom);
// get all elements with a particular id and then loop through and print the href attribute
$elements = $xPath->query('//*[@id="content"]/p/span');
$nodeName = $elements->item(0)->nodeName;
// $content = $elements->item(0)->nodeValue;
$content = $dom->saveXml($elements->item(0));
$content = $dom->saveHtml($elements->item(0));
$content = preg_replace(array("#^<{$nodeName}.*>#isU", "#</{$nodeName}>$#isU"), array('', ''), $content);
echo $content;
PHP中文网PHP中文网2822 days ago426

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-10 15:57:50

    自己找到了办法。。。

    $content = $elements->item(0)->nodeValue;
    
    // >> 改成 >>
    
    $content = $dom->saveXml($elements->item(0));

    reply
    0
  • Cancelreply