Question

I am currently using PHP's file_get_contents($url) to fetch content from a URL. After getting the contents I need to inspect the given HTML chunk, find a 'select' that has a given name attribute, extract its options, and their values text. I am not sure how to go about this, I can use PHP's simplehtmldom class to parse html, but how do I get a particular 'select' with name 'union'

<span class="d3-box">
  <select name='union' class="blockInput" >
    <option value="">Select a option</option> ..

Page can have multiple 'select' boxes and hence I need to specifically look by name attribute

<?php 
    include_once("simple_html_dom.php");
    $htmlContent = file_get_contents($url);
    foreach($htmlContent->find(byname['union']) as $element)
    echo 'option : value'; 
?>

Any sort of help is appreciated. Thank you in advance.

Was it helpful?

Solution

Try this PHP code:

<?php

require_once dirname(__FILE__) . "/simple_html_dom.php";

$url = "Your link here";

$htmlContent = str_get_html(file_get_contents($url));
foreach ($htmlContent->find("select[name='union'] option") as $element) {
    $option = $element->plaintext;
    $value  = $element->getAttribute("value");
    echo $option . ":" . $value . "<br>";
}

?>

OTHER TIPS

how about this:

$htmlContent = file_get_html('your url');
$htmlContent->find('select[name= "union"]');

in object oriented way:

  $html = new simple_html_dom();
  $htmlContent = $html->load_file('your url');
  $htmlContent->find('select[name= "union"]');

From DOMDocument documentation: http://www.php.net/manual/en/class.domdocument.php

$html = file_get_contents( $url );
$dom = new DOMDocument();
$dom->loadHTML( $html );

$selects = $dom->getElementsByTagName( 'select' );
$select = $selects->item(0);

// Assuming all children are options.
$children = $select->childNodes;

$options_values = array();
for ( $i = 0; $i < $children->length; $i++ )
{
  $item = $children->item( $i );
  $options_values[] = $item->nodeValue;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top