Search code examples
phpxpathcheckboxdomdocumentdomxpath

PHP XPath to determine if a checkbox is checked?


On a website it has a checkbox HTML code like this:

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

How do I check if the checkbox is already checked via the xPath? I essentially just want a boolean telling me True if it is checked. I am unsure how to get this though.

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

Solution

  • You're overthinking the XPath. evaluate() here evaluates the results of the XPath string - there's no need to turn it into a PHP expression to be evaluated.

    $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";
    }