Search code examples
phpsymfonyselectxmldocumentxmldom

Select value instead of text from option + XML DOM


I'm trying to get the values of a select list with the name = Reeks that you can find on this page: http://www.volleyvvb.be/?page_id=1083. The select list looks like this:

<select class="vvb_tekst_middelkl" name="Reeks" onchange="this.form.submit();">
    <option value="%" selected="">ALLE REEKSEN</option>
    <option value="Liga A H">ETHIAS VOLLEY LEAGUE</option>
    <option value="Liga B H">LIGA B HEREN</option>
    <option value="Ere D">LIGA A DAMES</option>
    ...
</select>

This is how I get the select list:

$html = file_get_contents("http://www.volleyvvb.be/?page_id=1083");

$crawler = new Crawler($html);

$crawler = $crawler->filter("select[name='Reeks']");
foreach ($crawler as $domElement) {
    foreach($domElement->childNodes as $child) {
        $value = $child->nodeValue;
        var_dump($value);
    }
}

What I see now is all the lines between the <option></option> like ALLE REEKSEN, ETHIAS VOLLEY LEAGUE. But I would also like the values like Liga A H, ... How can I select them?


Solution

  • The following code

    <?php
    require_once("resources/simple_html_dom.php");
    $html = file_get_contents("http://www.volleyvvb.be/?page_id=1083");
    $doc = str_get_html($html);
    
    $select = $doc->find("select[name='Reeks']");
    foreach ($select as $domElement) {
        $child = $domElement->find('option');
        foreach($child as $option) {
            echo $option->getAttribute('value')."<br>";
        }
    }
    ?>
    

    gives me the output you requested.

    Liga A H
    Liga B H
    Ere D
    ...
    

    An equivalent for the DomCrawler Component would be

    $value = $child->nodeValue; // LIGA B HEREN, ...
    $attribute = $child->attr('value'); // Liga B H, ...
    

    For further details take a look at the Documentation here.