这里有一个简单的例子来演示PHP Simple HTML DOM Parser的用法。
它演示了访问输入字段的“类型”和“值”。
<?php
include __DIR__ .'/vendor/simplehtmldom_1_5/simple_html_dom.php';
// restrict the list of names to use
$inputNames = array("nama", "kontak", "email", "userid", "foto", "id_jabatan", "simpan");
if (empty($_POST)) { // supply default values
$_POST = array();
foreach ($inputNames as $name) {
$_POST[$name] = '';
}
}
$html = <<<EOF
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<form action="" method="post">
Nama : <input type="text" name="nama" value="{$_POST['nama']}" ><br />
Kontak : <input type="text" name="kontak" value="{$_POST['kontak']}"><br />
Email : <input type="text" name="email" value="{$_POST['email']}"><br />
UserID : <input type="text" name="userid" value="{$_POST['userid']}"><br />
Foto : <input type="file" name="foto" value="{$_POST['foto']}"><br />
<input type="hidden" name="id_jabatan" value="2"><br>
<br />
<input type="submit" value="Simpan" name="simpan">
</form>
</body>
</html>
EOF;
// parse the HTML and the POST inputs.
if (!empty($_POST)) {
$htmlDom = str_get_html($html);
// find all the elements with a name
$elements = $htmlDom->find('[name]');
foreach ($elements as $node) {
if (!in_array($node->attr['name'], $inputNames)) {
continue; // ignore
}
echo 'The Name is: ', $node->attr['name'], ' ',
'The Tag/Type is: ', $node->tag, ' ', ' / ', $node->attr['type'], ' ',
'The Value is: ', $node->attr['value'], '<br />';
}
}
// show the form with the current values.
echo '<br />';
echo $html;
exit;
输出:
The Name is: nama The Tag/Type is: input / text The Value is:
The Name is: kontak The Tag/Type is: input / text The Value is:
The Name is: email The Tag/Type is: input / text The Value is: xxx@ttt
The Name is: userid The Tag/Type is: input / text The Value is:
The Name is: foto The Tag/Type is: input / file The Value is: Winter.jpg
The Name is: id_jabatan The Tag/Type is: input / hidden The Value is: 2
The Name is: simpan The Tag/Type is: input / submit The Value is: Simpan
Nama :
Kontak :
Email :
UserID :
Foto :