2024 PHP Conference Japan

dBase

新增註解

使用者貢獻的註解 1 則註解

匿名
15 年前
很遺憾, dbase 函式沒有被編譯到我的商業伺服器的 PHP 中,而我需要讀取一些包含 dbfs 資料的地理數據形狀檔案。

所以這也許能幫助其他人

<?php
function echo_dbf($dbfname) {
$fdbf = fopen($dbfname,'r');
$fields = array();
$buf = fread($fdbf,32);
$header=unpack( "VRecordCount/vFirstRecord/vRecordLength", substr($buf,4,8));
echo
'Header: '.json_encode($header).'<br/>';
$goon = true;
$unpackString='';
while (
$goon && !feof($fdbf)) { // read fields:
$buf = fread($fdbf,32);
if (
substr($buf,0,1)==chr(13)) {$goon=false;} // end of field list
else {
$field=unpack( "a11fieldname/A1fieldtype/Voffset/Cfieldlen/Cfielddec", substr($buf,0,18));
echo
'Field: '.json_encode($field).'<br/>';
$unpackString.="A$field[fieldlen]$field[fieldname]/";
array_push($fields, $field);}}
fseek($fdbf, $header['FirstRecord']+1); // move back to the start of the first record (after the field definitions)
for ($i=1; $i<=$header['RecordCount']; $i++) {
$buf = fread($fdbf,$header['RecordLength']);
$record=unpack($unpackString,$buf);
echo
'record: '.json_encode($record).'<br/>';
echo
$i.$buf.'<br/>';} //raw record
fclose($fdbf); }
?>

這個函式只是使用 echo 和 json_encode 傾印整個檔案,因此您可以根據自己的需求進行調整...(例如,隨機存取只需將 seek 改為:fseek($fdbf, $header['FirstRecord']+1 +($header['RecordLength']* $desiredrecord0based);移除 for 迴圈並返回 $record)

這個函式不做任何類型轉換,但它會提取類型,如果您需要處理日期或整理數字等。

雖然快速且簡陋,但可能對某些人有用,並且說明了 unpack 的強大功能。

Erich
To Top