Search code examples
phpsimple-html-dom

Parsing drop down menu with php simple dom


I want to parse this drop down menu with php simple dom.

<select name="example">  
    <option value="1">First example</option>  
    <option value="2">Second example</option>  
    <option value="3">Third example</option>
</select>

I need the values and the options for this drop down menu.


Solution

  • Like this :

    $dom = new DOMDocument("1.0", "utf-8");
    $dom->formatOutput = true;
    $dom->loadXML($YOUR_XML_STRING);
    $xpath = new DOMXPath($dom);
    $res = $xpath->query('//option');
    for ($i = 0; $i < $res->length; $i++) {
        $node = $res->item($i);
        $value = $node->getAttribute('value');
        $content = $node->nodeValue;
    }
    

    With PHP simple dom :

        $html = str_get_html($YOUR_DROPDOWN_MENU);
        $opt = $html->find('option');
        for ($i = 0; $i < count($opt); $i++) {
            $element = $opt[$i];
            $value = $element->value;
            $content = $element->innertext;
        }