how to take the value of each input and play each one in a variable

Asked

Viewed 135 times

2

Good afternoon guys! I am doing this way to get the value of each input that is within the $html variable

I have tried other methods to decrease that much of foreach for each input, more unsuccessfully.

as I do to use only a foreach or something of the type, to search all inputs, take the values and put each one in a variable .

I’m doing like this.

$html = '
<html>
  <body>
<input name="nome" id="nome" value="carlos" type="hidden">
<input name="sobrenome" id="sobrenome" value="silva" type="hidden">
<input name="nascimento" id="nascimento" value="1992" type="hidden">
</body>
</html>
';

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

foreach ($xpath->query("*/input[@name='nome']") as $p) {
  $nome = $p->getAttribute('value');
}
foreach ($xpath->query("*/input[@name='sobrenome']") as $p) {
  $sobre= $p->getAttribute('value');
}
foreach ($xpath->query("*/input[@name='nascimento']") as $p) {
  $nasc= $p->getAttribute('value');
}
## RESULTADOS
echo '<b style="color:red;">NOME:</b> <br />' . $nome;
echo '<br /><b style="color:red;">SOBRENOME:</b> <br />' . $sobre;
echo '<br /><b style="color:red;">DATA DE NASCIMENTO:</b> <br />' . $nasc;
  • What kind of input is this? form?

  • that is the input of a common form, and pq the site did not send code :/ ex: '< input name="name" id="name" type="text">' .. < input name="last name" id="last name" type="text"> .. < input name="birth" id="birth" type="text">

1 answer

1


Try this way:

$variavel = '<html>
<body>
<input name="nome" id="nome" value="carlos" type="hidden">
<input name="sobrenome" id="sobrenome" value="silva" type="hidden">
<input name="nascimento" id="nascimento" value="1992" type="hidden">
</body>
</html>';

$dom = new DOMDocument();
$dom->preserveWhiteSpace = true;
$dom->loadHTML($variavel);

//use DomXPath para encontrar os inputs
$xpath = new DomXPath($dom);
$classname='desaparecer';
$xpath_results = $xpath->query("//input");

$dados = [];

foreach( $xpath_results as $input ) {
    $dados[$input->getAttribute('name')] = $input->getAttribute('value');
}

unset($dom); //limpa a memoria

var_dump( $dados );

  • kkkkkk vlw bro, worse than I had ever tried it.. more as I am novice did not know how to make the code to get Kd a > $data['name']; .. now worked rsssrrs

  • tranquil.... you came very close...rs give a vote on my answer q everyone gets happy :D

  • rsrs worst q I came close even.. tmj vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.