Reputation: 123
I have an HTML string inside a PHP variable. The string contains several input fields. How can I get the value of an input field by its ID?
$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';
Upvotes: 2
Views: 5244
Reputation:
One possibility is to use PHP Simple HTML DOM.
Here's an example for finding an input element by ID and printing its value:
<?php
$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';
// Create DOM from URL or file
$html = str_get_html($text);
foreach($html->find('input') as $element) {
if($element->id == "test1") {
echo "Element: #".$element->id." has value: ".$element->value;
}
}
?>
Upvotes: 2
Reputation: 11787
From what I can tell, you have an HTML string and you want to parse it as HTML, then find an element by its ID.
If you don't want to learn the somewhat initially confusing syntax for XML manipulation or write a probably convoluted regular expression, you could use a tool like phpQuery.
An example would look like:
$html = phpQuery::newDocument($text);
$result = pq($html)->find("#id");
Upvotes: 2
Reputation: 16828
While regular expressions are not the preferred method for parsing HTML, this is my solution:
<?php
$text = '<html><head></head><body><form action="" method="post"><label>Test</label><input type="text" name="test1" id="test1" value="Value Test" /><label>Test 2</label><input type="text" name="test2" id="test2" value="Value Test2" /></form></body></html>';
$id = 'test1';
preg_match_all("/<input type=\"text\"(.*)id=\"$id\" value=\"(.*?)\"(.*)>/",$text,$matches);
$value = '';
if(isset($matches[2][0])){
$value = $matches[2][0];
}
echo 'Value: '.$value;
Upvotes: 1
Reputation: 39
$_POST['test1'] $_POST['test2']
Of course you will need to use these inside of your php code, depending on what you are doing. My example will post the results to your action page.
<?php echo("Your name is ".$_POST['test1']."<BR>Your Age is ".$_POST['test2']); ?>
Upvotes: 1