PHP DOM Get< option>选择的标签 [英] PHP DOM Get <option> Tag That Is Selected
问题描述
因此,我们可以说HTML看起来像这样:
So let's say the HTML looks something like this:
<select name="some_name">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
</select>
我需要从那里提取属性为selected ="selected"的选项标签.我怎样才能做到这一点?到目前为止,我有这个:
I need to extract the option tag with attribute selected="selected" from there. How can I do that? So far I have this:
$string = file_get_contents('test.html');
include 'htmlpurifier-4.0.0-standalone/HTMLPurifier.standalone.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Doctype', 'XHTML 1.0 Strict');
$purifier = new HTMLPurifier($config);
$string = $purifier->purify($string);
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="UTF-8">' . $string);
$dom->preserveWhiteSpace = false;
$num = 0;
$optionTags = $dom->getElementsByTagName('option');
foreach ($optionTags as $o) {
if ($o->hasAttribute('selected')
&& 'selected' === $o->getAttribute('selected')) {
$num = $o->nodeValue;
}
}
echo $num;
那是行不通的.之后,$ num仍然等于零.
And that doesn't work. The $num is still equal to zero afterwards.
推荐答案
我认为它不起作用,因为您忘记了使用属性 item
来访问 DOMNodeList
的项目代码>.
I believe it does not work because you are forgetting to access the DOMNodeList
's item using its property item
.
尝试这种方法,遍历返回的 DOMNodeList
的整个长度.检查当前项目索引处的 DOMNode
是否具有名为"selected"
Try this approach, loop through the entire length of the DOMNodeList
returned. Checked if the DOMNode
at the current item's index has an attribute named "selected"
$num = 0;
$optionTags = $dom->getElementsByTagName('option');
for ($i = 0; $i < $optionTags->length; $i++ ) {
if ($optionTags->item($i)->hasAttribute('selected')
&& $optionTags->item($i)->getAttribute('selected') === "selected") {
$num = $optionTags->item($i)->nodeValue;
}
}
我的确切代码:
$dom = new DOMDocument();
$dom->load("C:\\test.htm");
$num = 0;
$optionTags = $dom->getElementsByTagName('option');
for ($i = 0; $i < $optionTags->length; $i++ ) {
if ($optionTags->item($i)->hasAttribute('selected')
&& $optionTags->item($i)->getAttribute('selected') === "selected") {
$num = $optionTags->item($i)->nodeValue;
}
}
echo "Num is " . $num;
输出:
数字为3
这篇关于PHP DOM Get< option>选择的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!