PHP DOMXPath 查询使用元素的innerHTML/nodeValue 来查找并返回该元素
当您想要检查元素的innerHTML/nodeValue 时,您能帮我使用正确的语法吗?
我对名称没有问题,但是年龄位于普通的 div 元素内,使用什么正确的语法来代替下面的“不确定要放什么”。
$html 是来自互联网的页面
人名在一个跨度中,例如:
<span class="fullname">John Smith</span>
人的年龄在一个 div 中,例如:
<div>Age: 28</div>
我有以下 PHP:
<?php
$dom = new DomDocument();
@$dom->loadHTML($html);
$finder = new DOMXPath($dom);
//Full Name
$findName = "fullname";
$queryName = $finder->query("//span[contains(@class, '$findName')]");
$name = $queryName->item(0)->nodeValue;
//Age
$findAge = "Age: ";
$queryAge = $finder->query("//div[NOT SURE WHAT TO PUT HERE]");
$age = substr($queryAge->item(0)->nodeValue, 5);
?>
Can you please help me with the correct syntax to use when you want to check the innerHTML/nodeValue of an element?
I have no problem with the Name however the Age is within a plain div element, What is the correct syntax to use in place of "NOT SURE WHAT TO PUT HERE" below.
$html is a page from the internet
The persons name is in a span like:
<span class="fullname">John Smith</span>
The persons age is in a div like:
<div>Age: 28</div>
I have the following PHP:
<?php
$dom = new DomDocument();
@$dom->loadHTML($html);
$finder = new DOMXPath($dom);
//Full Name
$findName = "fullname";
$queryName = $finder->query("//span[contains(@class, '$findName')]");
$name = $queryName->item(0)->nodeValue;
//Age
$findAge = "Age: ";
$queryAge = $finder->query("//div[NOT SURE WHAT TO PUT HERE]");
$age = substr($queryAge->item(0)->nodeValue, 5);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下,
由于空格,我在
starts-with()
方面取得了有限的成功,因此您可能不得不求助于是否有机会发现误报(即其他带有“Age:”的 div) ),您也许可以通过使用更具体的路径(如果已知)来避免这种情况,即
Try
I've had limited success with
starts-with()
due to whitespace so you may have to resort toIf there's a chance of finding false positives (ie, other divs with "Age: " in them), you might be able to avoid that by using a more specific path (if known), ie