PHP DOMXPath查询使用元素的innerHTML / nodeValue查找并返回该元素 [英] PHP DOMXPath query using the innerHTML/nodeValue of an element to find and return the element

查看:359
本文介绍了PHP DOMXPath查询使用元素的innerHTML / nodeValue查找并返回该元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您要检查元素的innerHTML / nodeValue时,能否请您帮我使用正确的语法?

Can you please help me with the correct syntax to use when you want to check the innerHTML/nodeValue of an element?

名称没有问题年龄位于一个普通的div元素内,下面的不能确定在此放置什么的正确语法是什么?

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是互联网

$html is a page from the internet

人名的范围如下:

<span class="fullname">John Smith</span>

人的年龄在div中,例如:

The persons age is in a div like:

<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);
?>


推荐答案

尝试

$queryAge = $finder->query("//div[starts-with(., '$findAge')]");

我通过 starts-with()由于存在空格,因此您可能不得不求助于

I've had limited success with starts-with() due to whitespace so you may have to resort to

$queryAge = $finder->query("//div[contains(., '$findAge')]");

如果有可能发现误报(例如,其他带有 Age:的div) ,您可以通过使用更具体的路径(如果已知)来避免这种情况,即

If 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

$queryAge = $finder->query("//div[@id='something']//div[contains(., '$findAge')]");

这篇关于PHP DOMXPath查询使用元素的innerHTML / nodeValue查找并返回该元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆