由於 PHP 沒有類似 snmptable 的好用函式... 以下是一個對我來說可用的快速且簡陋的技巧。適用於完整和稀疏的表格。範例 OID 適用於路由 (完整) 和介面 (通常是稀疏的) 表格。
<?php
$a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.4.21") or die("error");
print_r($a);
$a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.2.2") or die("error");
print_r($a);
function snmptable($host, $community, $oid) {
// TODO: get original state and restore at bottom
snmp_set_oid_numeric_print(TRUE);
snmp_set_quick_print(TRUE);
snmp_set_enum_print(TRUE);
$retval = array();
$raw = snmprealwalk($host, $community, $oid) or die("snmptable: unable to walk OID $oid");
$prefix_length = 0;
foreach ($raw as $key => $value) {
if ($prefix_length == 0) {
// don't just use $oid's length since it may be non-numeric
$prefix_elements = count(explode('.',$oid));
$tmp = '.' . strtok($key, '.');
while ($prefix_elements > 1) {
$tmp .= '.' . strtok('.');
$prefix_elements--;
}
$tmp .= '.';
$prefix_length = strlen($tmp);
}
$key = substr($key, $prefix_length);
$index = explode('.', $key, 2);
isset($retval[$index[1]]) or $retval[$index[1]] = array();
isset($firstrow) or $firstrow = $index[1];
$retval[$index[1]][$index[0]] = $value;
}
// check for holes in the table and fill them in
foreach ($retval[$firstrow] as $key => $tmp) {
foreach($retval as $check => $tmp2) {
if (! isset($retval[$check][$key])) {
$retval[$check][$key] = '';
}
}
}
return($retval);
}
?>