Reputation: 915
I have a html file loaded as a string in php, and I need to get the values of the input elements in the HTML string. Can someone help me build a function which takes the name of the input element and returns its value?
This is an example of the function I would like to do:
function getVal($name){
$htmlStr = "<form action = \"action.php\"><input type=\"hidden\" name=\"command\" value=\"123456\">
<input type=\"hidden\" name=\"quantity\" value=\"1\">
<input type=\"hidden\" name=\"user_mode\" value=\"1\">
<input type=\"hidden\" name=\"stock\" value=\"-1255303070\">
<input type=\"hidden\" name=\"id\" value="429762082">
<input type=\"hidden\" name=\"pidm\" value=\"2\"></form>";
// I'd like to get the value of $name here probably using preg_match
return $value; //returns 123456
}
$val = getVal("command"); //val should be 123456.
any idas? Thank you
Upvotes: 2
Views: 6975
Reputation: 67735
Load the HTML in a DOMDocument
, then a simple XPath query would to the trick:
$xpath = new DOMXPath($domDocument);
$items = $xpath->query('//*[@name="command"]/@value');
if ($items->length)
$value = $items->item(0)->value;
Upvotes: 1
Reputation: 16951
Here is an example with DOM:
$html = "<form action = \"action.php\">
<input type=\"hidden\" name=\"command\" value=\"123456\">
<input type=\"hidden\" name=\"quantity\" value=\"1\">
<input type=\"hidden\" name=\"user_mode\" value=\"1\">
<input type=\"hidden\" name=\"stock\" value=\"-1255303070\">
<input type=\"hidden\" name=\"id\" value=\"429762082\">
<input type=\"hidden\" name=\"pidm\" value=\"2\">
</form>";
$document = new DOMDocument();
$document->loadHTML($html);
$inputs = $document->getElementsByTagName("input");
foreach ($inputs as $input) {
if ($input->getAttribute("name") == "id") {
$value = $input->getAttribute("value");
}
}
echo $value;
Upvotes: 8