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

2

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

I have tried other methods to decrease this amount of foreach for each input, but without success.

How do I use just a foreach or something like that, to fetch all inputs, get the values and put each one into a variable.

I'm doing 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;
    
asked by anonymous 02.03.2018 / 19:07

1 answer

1

Try this:

$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 );
    
02.03.2018 / 19:16