开发者

php get selected option

I am processing files that contain HTML markup.

I need to get the selected option from the drop down box. In this 开发者_运维技巧case Australia is the selected option ..

  <select name="cCountry" id="cCountry" style="width:200" tabindex="5">

  <option value="251">Ascension Island</option>
  <option selected="selected" value="14">Australia</option>
  <option value="13">Austria</option>

Another scenario :

    <select name="cBirthYearM" id="cBirthYearM">
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option selected="selected" value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>

In this case '1977" is the value that I need to extract as it's the selected option . To make it clear I need to get the value from the markup not from user GET/POST input


The value specified in the value part of the option will be in $_GET ['cCountry'] or $_POST ['cCountry'] (depending if you're using GET or POST to submit the form).

It should be simple matter to look up the value from a lookup table or DB query.

EDIT: This question didn't make it clear if you meant how to get the value the user selected when the form is submitted, or how to get the value from the markup. If it's the latter, then you should look at DOMDocument.


If you wish to parse HTML in PHP then the preferred method is the DOM hierarchy of objects, especially DOMDocument. You can use Javascript-like methods of accessing the DOM tree such as getElementById to grab the select control (in this case getElementById ('cCountry')) and then examine its children (the options) to find the selected one and get its attributes.

It can take a little getting used to using the DOM objects but they're far more powerful for parsing and manipulating HTML than regex would be, so they're well worth learning.

  • http://php.net/manual/en/book.dom.php
  • http://php.net/manual/en/class.domdocument.php
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜