Search code examples
phpsimplexmlselected

Can I find selected options in a form using simplexml?


I'm able to find a select's options on a website using the following code:

$dom = new DOMDocument();
$dom->loadHTMLFile('http://webseven.com.au/carl/testpage.htm');
$xml = simplexml_import_dom($dom);
//print_r($xml);
$select = $xml->xpath('//table/tr/td/select');
print_r($select);

I get (as an example)

[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [name] => product_OnWeb
                [tabindex] => 4
            )

        [option] => Array
            (
                [0] => Yes
                
                [1] => No
                 
        
            )

    )

But I cannot find a way to find which of those is selected. Can this be done with SimpleXML or is there another method?


Solution

  • You need to loop through all the options (using foreach ( $node->option ... )), and check for the selected attribute (using $node['selected']):

    $dom = new DOMDocument();
    $dom->loadHTMLFile('http://webseven.com.au/carl/testpage.htm');
    $xml = simplexml_import_dom($dom);
    
    $selects = $xml->xpath('//table/tr/td/select');
    foreach ( $selects as $select_node )
    {
        echo $select_node['name'] . ': ';
    
        foreach ( $select_node->option as $option_node )
        {
            if ( isset($option_node['selected']) )
            {
                echo $option_node['value'] . ' ';
            }
        }
    
        echo "\n";
    }
    

    As an aside, you are likely to be led astray if you use print_r to debug SimpleXML, as it doesn't show you the true state of the object. I've written a simplexml_dump function which might be more useful.