Mike Jenkins
Mike Jenkins

Reputation: 338

Get all <option>s from <select> using getElementById

I need to get all of the <option> data from a <select> in an HTML document using PHP. The code that I have at the moment:

$pageData = $this->Http->get($this->config['url']);
libxml_use_internal_errors(true);
$this->Dom->loadHTML($pageData);
$select = $this->Dom->getElementById('DDteam');

I am not sure how, from here, to get the value of each of the options and also the text inside the option tags. I can't inspect the object using print_r or similar either.

Upvotes: 4

Views: 2424

Answers (1)

vstm
vstm

Reputation: 12537

You have to use the DOM-API to retrieve the data you want. Since the <select> element is not that complex you can fetch all the <options>-nodes using getElementsByTagName:

$select = $this->Dom->getElementById('DDteam');
$options = $select->getElementsByTagName('option');

$optionInfo = array();
foreach($options as $option) {
    $value = $option->getAttribute('value');
    $text = $option->textContent;

    $optionInfo[] = array(
        'value' => $value,
        'text' => $text,
    );
}

var_dump($optionInfo);

Upvotes: 5

Related Questions