DomXML xpath 接下来我该怎么办?
我有这样的代码:
$reader = new DOMDocument();
$reader->loadHTML($shell);
$xpath = new DomXPath($reader);
$xpath->registerNamespace('html','http://www.w3.org/1999/xhtml');
$res = $xpath->query('descendant-or-self::*[contains(@class,"content")]');
print_r($res);
$shell 只是一个包含以下 html 代码的变量:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<title>Hello World</title>
</head>
<body>
<div class="content">
Hello World!!
</div>
</body>
</html>
如果我是正确的 xpath 查询:
descendant-or-self::*[contains(@class,"content")]
应该获取带有“content”类的 div。但是,当我打印数组时,我看到的只是一个空对象:
DOMNodeList Object
(
)
这是否意味着查询不起作用? DomXPath 查询语言与 SimpleXML Xpath 查询语言是否不同,因为查询使用 SimpleXML?
如果工作正常,如何查看和修改匹配的节点?
I have this code:
$reader = new DOMDocument();
$reader->loadHTML($shell);
$xpath = new DomXPath($reader);
$xpath->registerNamespace('html','http://www.w3.org/1999/xhtml');
$res = $xpath->query('descendant-or-self::*[contains(@class,"content")]');
print_r($res);
$shell is just a variable containing the following html code:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en-us" />
<title>Hello World</title>
</head>
<body>
<div class="content">
Hello World!!
</div>
</body>
</html>
If I am correct the xpath query:
descendant-or-self::*[contains(@class,"content")]
is supposed to get the div with the class "content". However when I print the array all I see is an empty object:
DOMNodeList Object
(
)
Does this mean that the query didnt work? Is the DomXPath query language different to the SimpleXML Xpath one, because the query works with SimpleXML?
If it is working how do I view and modify the matched nodes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
print_r
- 处理DOMNodeList
(或任何 DOM 类)对您没有多大好处:它们主要是在 C / Libxml2 级别实现的,而不是本机实现的接触PHP。据我所知,这会起作用,在查询后添加它,看看是否得到结果:print_r
- ing aDOMNodeList
(or any of the DOM-classes) doesn't do you much good: they're mostly implemented at C / Libxml2 level, and not natively exposed to PHP. As far as I can tell, this will work, add this after your query, and see if you get results:我想你想要这样的东西:
//*[@class='content']
这将获得带有类内容的任何标签。
获取任意 div 会稍微更具可读性:
//div[@class='content']
在 xpath 中,您可以使用
//
运算符来获取dom 中任何级别的标记。它将匹配所有这些。I am thinking you want somthiing like this:
//*[@class='content']
This will get any tag with the class content.
It will be slightly more readable to just get the any div:
//div[@class='content']
In xpath, you use the
//
operator to grab a tag at any level in the dom. It will match them all.