我需要使用 PHPQuery 根据下拉列表的 id
获取数组中下拉列表的所有值。
HTML如下:
<select name="semester" id="semester" class="inputtxt" onChange="javascript:selectSemester(this, this.form);">
<option value="">-- Select your Semester --</option>
<option value="2nd" selected>2nd</option>
<option value="4th" >4th</option>
<option value="6th" >6th</option>
<option value="8th" >8th</option>
<option value="SE1" >SE1</option>
<option value="SE3" >SE3</option>
<option value="SE5" >SE5</option>
<option value="SE7" >SE7</option>
</select>
我试过这个:
$semesters = $all['#semester'];
foreach ($semesters as $semester) {
echo pq($semester)->text();
echo '<br>';
}
但我只得到一个所有值串联的输出。如何将每个值作为数组中的单独元素获取?
最佳答案
这段代码对我来说很好用:
// include part...
$ids = array();
$raw = file_get_contents("http://localhost:8000/test.html"); // your url
$doc = phpQuery::newDocument($raw);
phpQuery::selectDocument($doc);
/** @var DOMElement $opt */
foreach (pq('#semester > option') as $opt) {
$ids[] = ($opt->getAttribute('value'));
}
print_r($ids); // check if the array has the values stored
所以结果是
Array
(
[0] =>
[1] => 2nd
[2] => 4th
[3] => 6th
[4] => 8th
[5] => SE1
[6] => SE3
[7] => SE5
[8] => SE7
)
顺便说一句,您可以使用 $doc['#semester > option']
而不是 pq('#semester > option')
,两种变体都可以正常工作。如果你需要省略一些 option
- 你会根据 option
属性制作过滤器,比如 if ($opt->getAttribute('value') != "")
.
关于PHPQuery 从下拉列表中选择所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31510836/