我可以使用simplexml在表单中找到选定的选项吗


Can I find selected options in a form using simplexml?

我可以使用以下代码在网站上找到select的选项:

$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);

我得到(举个例子)

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

但我找不到一种方法来找出其中哪一个是被选中的。这可以用SimpleXML完成吗?或者还有其他方法吗?

您需要循环浏览所有选项(使用foreach ( $node->option ... )),并检查selected属性(使用$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";
}

顺便说一句,如果使用print_r调试SimpleXML,您很可能会误入歧途,因为它不会向您显示对象的真实状态。我已经编写了一个simplexml_dump函数,它可能更有用。

相关文章: