Search code examples
phpdomdocument

Curl php - if condition


HTML

<select id="myid">
    <option value="1" data-name="text 1" data-price="5">Text 1</option>
    <option value="2" data-name="text 2" data-price="10">Text 2</option>
</select>

My code below works fine but show me all the "data-price" with TagName "option". I would like to grab only one specif price. So I would like to add something like this:

<?php
$doc = new DOMDocument();
@$doc->loadHTMLFile('https://example.com');
$optionNodes = $doc->getElementById('myid')->getElementsByTagName('option');
foreach($optionNodes as $optionNode) {
// if $optionNode->getAttribute('data-name') = "text 2"
     echo $optionNode->getAttribute('data-price') . '<br/>';
}
?>

Any help would be appreciated.

Thanks


Solution

  • XPath to the rescue.

    <?php
    $doc = new DOMDocument();
    @$doc->loadHTMLFile('https://example.com');
    $xp=new DOMXPath($doc);
    echo $xp->query("//option[@value='2']")->item(0)->getAttribute("data-price");
    
    • gets the first element with the attribute value="2" and fetches it's data-price attribute.

    likewise you can do

    echo $xp->query("//option[@data-name='text 2']")->item(0)->getAttribute("data-price");
    

    to fetch it by data-name, or you can even do

    echo $xp->query("//option[text()='Text 2']")->item(0)->getAttribute("data-price");
    

    to fetch it based on the text content, and even

    echo $xp->query("//option[contains(text(),'Text 2')]")->item(0)->getAttribute("data-price");
    

    to fetch it based on partial text content (this will fetch any option element which has Text 2 anywhere in it's textContent.)