PHP xpath提取网页数据内容代码解析

2025-05-29 0 53

想要使用xpath来解析html内容, PHP自带两个对象

DOMDocument,DOMXpath,其中初始化 loadHtml一般都会报很多警告,但是并不影响使用,用@屏蔽错误。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
/**

* 初始化DOMXpath对象

*

* @param [type] $content 网页内容

* @param [array] $pathinfo 匹配信息

*

* @return void

*/

private function _createXpathObj($content, $patinfo)

{

// 如果没有xpath配置项,不初始化xpath

if (!$this->_existsXpathParse($patinfo)) {

return;

}

try {

$dom = new \\DOMDocument();

@$dom->loadHtml($content);

$dom->normalize();

$xpath = new \\DOMXpath($dom);

$this->xpathObj = $xpath;

} catch (\\Exception $e) {

getService('logger')->warning('Parse html fail', ['content' => $content]);

}

}

其中 $node 为 DOMElement 对象。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
/**

* 获取Xpath解析值

*

* @param [type] $pat 匹配模式

*

* @return string

*/

private function _getXpathField($pat)

{

$objs = $this->xpathObj->query($pat);

if ($objs->length > 0) {

$node = $objs->item(0);

$outerHTML = $node->ownerDocument->saveHTML($node);

return trim($outerHTML);

# 作为示例 输出innerhtml

//$innerHTML = '';

//foreach ($node->childNodes as $childNode){

// $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);

//}

//return $innerHTML;

# 作为示例 输出文本不含标签

//return $node->textContent; //$node->nodeValue;

}

return '';

}

示例

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
<?php

$dom = new DOMDocument('1.0','UTF-8');

$dom->loadHTML('<html><body><div><p>p1</p><p>p2</p></div></body></html>');

$node = $dom->getElementsByTagName('div')->item(0);

$outerHTML = $node->ownerDocument->saveHTML($node);

$innerHTML = '';

foreach ($node->childNodes as $childNode){

$innerHTML .= $childNode->ownerDocument->saveHTML($childNode);

}

echo '<h2>outerHTML: </h2>';

echo htmlspecialchars($outerHTML);

echo '<h2>innerHTML: </h2>';

echo htmlspecialchars($innerHTML);

?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://www.cnblogs.com/wangluochong/p/13222665.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP xpath提取网页数据内容代码解析 https://www.kuaiidc.com/91055.html

相关文章

发表评论
暂无评论