How to get value in this select using simple-html-dom? - php

<select name="size_select" class="long form-control">
<option selected="selected" value="">Please select</option>
<option value="6 (xxs)" title="6 (XXS)">6 (XXS)</option>
<option value="8 (xs)" title="8 (XS)">8 (XS)</option>
<option value="10 (s)" title="10 (S)">10 (S)</option>
<option value="12 (m)" title="12 (M)">12 (M)</option>
<option value="14 (l)" title="14 (L)">14 (L)</option>
<option value="16 (xl)" title="16 (XL)">16 (XL)</option>
<option value="18 (xxl)" title="18 (XXL)">18 (XXL)</option>
<option value="20 (xxxl)" title="20 (XXXL)">20 (XXXL)</option>
How to get all value in this select?
$element = $html->find('#sizeDdl',0);
foreach($element as $elemen) {
echo ($elemen->plaintext);
}
I try this output:
Notice: Trying to get property of non-object in /h2/home/website/website.com/test.php on line 11
The idea is that each individual value should be taken and recorded in SQL base. Now is a common result , not every value separately

First add id in select tag as
<select name="size_select" id="sizeDdl" class="long form-control">
then change these lines
$element = $html->find('#sizeDdl',0);
foreach($element as $elemen) {
echo ($elemen->plaintext);
}
to these:
$text_array = array();
$html = "Your html";
foreach($html->find('#sizeDdl') as $element) {
$options = $element->find('option');
foreach($options as $element1) {
$text_array[] = ($element1->plaintext);
}
}
var_dump($text_array);
print_r(text_array);

change this line
<select name="size_select" class="long form-control">
to this line
<select name="size_select" id="sizeDdl" class="long form-control">
as your dom element should have id attribute which u r using in javascript and missing in html.

There is two issues with your current code.
1) You are trying to fetch an element by an id that does not exist.
2) You are iterating through a list of elements, not its children.
Either find the element by name or give it an id (sizeDbl) and iterate its children (the options) instead.
You could also modify the selector to select a list of the children instead of the select itself:
$options = $html->find('#sizeDdl option');
or
$options = $html->find('#sizeDbl')->find('option');

for getting select values with simple html dom
just try this code it will help you
$element = $html->find('#selectIDGoesHere',0)->find('option');
foreach($element as $elemen) {
echo "Display text:".($elemen->plaintext)."<br>";
echo "value:".($elemen->value)."<br>";
}

Related

How do I get the selected option value as a string in PHP?

My aim is to get the selected item from the drop down and covert it to type string. After conversion, am comparing the result with another string and then use if() statement to execute some code. But the conversion does not seem to work because the program only execute else() statement. How can I do this? somebody help Please.
Below is my html and php code.
<select name="p_category">
<option selected disabled >-- select --</option>
<option value="computers">Computer</option>
<option value="phones" >Phone</option>
<option value="accessories">Accessory</option>
<option value="general">Display</option>
</select>
<?php
$getCategory = $_POST['p_category'];
$value = strval($getCategory);
$comps = "computer";
if($value == $comps){
echo "<script>alert('Equal')</script>";
}else{
echo "<script>alert('Not equal')</script>";
}
?>

Finding the value of an option with specific string

Consider this snippet from select form:
<select name="cat_id"">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
Is there a way, using SIMPLE DOM, I can extract the value="x" for specific string.
Example, I want to get the value of Dew, hence, I must be able to get 50
Tried searching and playing, but cannot find exact answer:
Parsing drop down menu with php simple dom <-- But values doesn't start from 0 nor increments uniformly
php , simple_html_dom.php, get selected option <-- I do not even have selected entry in the select form
I need to get the value for specific string so that I can use it to send form using cURL.
Hope, somebody can help. Thanks in advance and more power.
The following code will parse all option nodes and when the searched text is matched, it will display the corresponding value and ends:
$input = <<<_DATA_
<select name="cat_id">
<option value="33">Apple</option>
<option value="44">Banana</option>
<option value="48">Carrot</option>
<option value="50">Dew</option>
<option value="77">Eggplant</option>
<option value="84">Fern</option>
<option value="92">Grass</option>
</select>
_DATA_;
// Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($input);
// searched text
$searchText = 'dew';
// Create a regex pattern (match $searchText followed OR preceded by any number of spaces/tabs/newLines ...)
// i flag stands for case insensitive match
$pattern = '/\s*'.$searchText.'\s*/i';
foreach( $html->find('select[name="cat_id"] option') as $option ){
echo $string = $option->plaintext;
// Check if the current node contains the searched text
if( preg_match($pattern, $string) ){
$value = $option->value;
echo ' => ' . $value;
// Exit the loop when done
break;
}
echo '<br>';
}
OUTPUT
Apple
Banana
Carrot
Dew => 50

Retrieve name ID from php json file

I have this php file for country/state/town list using json method.
PHP file:
sleep(1);
$stateID = $_GET['stateID'];
$countyID = $_GET['countyID'];
$townID = $_GET['townID'];
$html = $_GET['html'];
$states = array();
$states['MA'] = "Massachusetts";
$states['VT'] = "Vermont";
$states['SC'] = "South Carolina";
$counties = array();
$counties['MA']['BARN'] = 'Barnstable';
$counties['MA']['PLYM'] = 'Plymouth';
$counties['VT']['CHIT'] = 'Chittenden';
$counties['SC']['ANDE'] = 'Anderson';
$towns = array();
$towns['MA']['BARN']['CHA'] = "Chatham";
$towns['MA']['BARN']['DEN'] = "Dennis";
$towns['MA']['BARN']['YAR'] = "Yarmouth";
$towns['MA']['PLYM']['BRI'] = "Bridgewater";
$towns['MA']['PLYM']['MAR'] = "Marshfield";
$towns['MA']['PLYM']['WAR'] = "Wareham";
$towns['VT']['CHIT']['BUR'] = "Burlington";
$towns['VT']['CHIT']['ESS'] = "Essex";
if($stateID && !$countyID && !$townID){
echo json_encode( $counties[$stateID] );
} elseif( $stateID && $countyID && !$townID ) {
echo json_encode( $towns[$stateID][$countyID] );
} elseif( isset($villages[$stateID][$countyID][$townID]) ) {
echo json_encode( $villages[$stateID][$countyID][$townID] );
} else {
echo '{}';
}
I retrieve value from MySql database(example:MA for country).
Now I need to print country/state/town name into select box dropdown like this.
<select id="country" class="validate[required]" name="country">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$country['selector'].'">Show Country Name From php File</option>
</select>
<select id="state" class="validate[required]" name="state">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$state['selector'].'">Show state Name From php File</option>
</select>
<select id="town" class="validate[required]" name="town">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$town['selector'].'">Show town Name From php File</option>
</select>
How can I print this?
Create a php file that makes the call to the database. The results are, normally, stored in a php array. You can turn this array into Json using json_encode()(http://www.php.net/manual/en/function.json-encode.php).
Simply echo this in the php-file.
Now call that script with jQuery. There is a simple jQuery method called getJson(). - Read more about it here: http://api.jquery.com/jquery.getjson/
This will bring the MySQL results to you - in Json form - and you could now use JavaScript to loop the results, and display the form accordingly. A simple example would be (I haven't tested this but I hope you get the idea):
$.each(data, function() {
$('#mySelect')
.append($("<option></option>")
.attr("value",data[row].NameOfColumn)
.text(value));
row ++;
});
Note the name of column - that's the name of the key for the value you are looking for. In your case you might want to loop the keys as well - with an outer loop - since the data seems to be presented in such a matter.

Select an option in a select box, given the option in word form in a PHP form

I have a standard select box in my php form for my website containing a list of counties in the UK, an example of which is shown below:
<p class='form_title'>County<br>
<select id="county" name="county">
<optgroup label="England">
<option>Bedfordshire</option>
<option>Berkshire</option>
<option>Bristol</option>
....
<option>Wiltshire</option>
<option>Worcestershire</option>
</optgroup>
<optgroup label="Wales">
<option>Anglesey</option>
...
<option>Radnorshire</option>
</optgroup>
<optgroup label="Scotland">
<option>Aberdeenshire</option>
...
<option>Wigtownshire</option>
</optgroup>
<optgroup label="Northern Ireland">
<option>Antrim</option>
...
<option>Tyrone</option>
</optgroup>
</select>
</p>
Once a user has submitted details, they can then edit them.
I therefore need a way to have selected the option that they previously chose, given that I have the option they chose saved in word form, such as Bedfordshire.
I know I need to add the word selected to one of the options, but I was wondering if there was a better way to do it than a massive case statement.
Thanks
You should set an option value for each option to track the value.
Also you should be generating that from a database and then you can set selected based on a $_GET or $_POST:
for example:
foreach($county as $name){
$selected = '';
if($name == $_GET['name']){
$selected = ' selected="selected"';
}
echo '<option value="'.$name.'"'.$selected.'>'.$name.'</option>';
}
this doesn't include your optgroup but that also should come from database.
Try something like this:
foreach($places as $place) {
$selected = $prevSelectionId == $place['id'] ? " selected='selected' " : "";
echo "<option $selected value='".$place['id']."'>".$place['name']."</option>";
}
</select>

Creating a select dropdown from a .txt?

I've a select menu hardcoded in a wordpress (php) theme, but the manager requires to edit those frequently. Is it possible to populate the select dropdown options from a text file import? So he just has to edit the text file and the menu options would change.
The current menu looks like this:
<select name="location" id="sort-location" class="sort-dropdown">
<option value="" selected="selected">LOCATION:</option>
<option value="" disabled="">--------------</option>
<option value="hongkong">Hong Kong</option>
<option value="taiwan">Taiwan</option>
<option value="mainland_china">Mainland China</option>
<option value="" disabled="">--------------</option>
<option value="">SHOW ALL</option>
</select>
Sure -- make yourself a small loop that runs through the lines in the format you choose.
<?php
$select = file_get_contents('select.txt');
$lines = explode("\n", $select);
foreach ($lines as $line) {
// let's say our format is like this:
// value|name|selected|disabled
// or:
// -
// for separator
if ($line == '-') {
echo '<option disabled="disabled">----------</option>';
} else {
list($value, $name, $selected, $disabled) = explode("|",$line);
echo '<option value="'.$value.'"',
$selected?' selected="selected"':'',
$disabled?' disabled="disabled"':'',
'>'.$name.'</option>';
}
}
?>
Sure, just fetch the text file into an array using file() and create the select out of it. A very simple implementation: menu.txt:
hongkong Hong Kong
taiwan Taiwan
mainland_china Mainland China
Note the tabs between value and label.
Then in PHP:
$menu_items = file("menu.txt");
foreach ($menu_items as $menu_item)
{
// Explode
$menu_item_exploded = explode("\t", $menu_item);
$option_value = htmlspecialchars(trim($menu_item_exploded[0]));
$option_label = htmlspecialchars(trim($menu_item_exploded[1]));
echo "<option value='$option_value'>$option_label</option>";
}
As far as I can see, you have the following left to solve:
How to pre-set a predefined value (You need to echo selected in the right item)
How to deal with the user editing out a value from the text file that was pre-set in your select.
Error handling if the file is not existent or not accessible
Error handling if the user screws up the line breaks, or something similar - maybe count the lines, and/or detect whether there are tabs inside the file

Categories