PHP XPath来确定是否选中了复选框



在网站上,它有一个复选框HTML代码,如下所示:

<input type="checkbox" name="mycheckbox" id="mycheckbox" value="123" checked="checked">

如何检查复选框是否已通过xPath选中?我本质上只是想要一个布尔值,如果它被选中,就会告诉我True。不过我不确定该怎么做。

<?php
$dom = new DOMDocument();
$content = file_get_content('https://example.com');
@$dom->loadHtml($content);
// Xpath to the checkbox
$xp = new DOMXPath($dom);
$xpath = '//*[@id="mycheckbox"]'; // xPath to the checkbox
$answer = $xp->evaluate('string(' . $xpath . ')');

您对XPath考虑太多了。evaluate()在这里计算XPath字符串的结果——不需要将其转换为要计算的PHP表达式。

$dom = new DOMDocument();
$content = '<html><body><input type="checkbox" name="mycheckbox" id="mycheckbox" value="123" checked="checked"></body></html>';
@$dom->loadHtml($content);
// Xpath to the checkbox
$xp = new DOMXPath($dom);
$xpath = '//*[@id="mycheckbox"]'; // xPath to the checkbox
$answer = $xp->evaluate($xpath);
// If we got an answer it'll be in a DOMNodeList, but as we're searching
// for an ID there should be only one, in the zeroth element
if ($answer->length) {
// Then we need to get the attribute list
$attr = $answer->item(0)->attributes;
// now we can check if the attribute exists and what its value is.
if ($chk = $attr->getNamedItem('checked')) {
echo $chk = $attr->getNamedItem('checked')->nodeValue;  //checked
} else {
echo "No checked attribute";
}
} else {
echo "Element with specified ID not found";
}

最新更新