Rodrigo
Rodrigo

Reputation: 5129

Strange behavior reading DBF file in PHP using fread()

I have a DBF file created as part of a shapefile with rgdal library's writeOGR function (in R).

When I ask to see its first bytes with Linux od command, I get the following.

od -x -c -N 32 BRA.dbf
0000000 7703 1e07 001b 0000 00a1 00d1 0000 0000
0000020 0000 0000 0000 0000 0000 0000 5700 0000
0000040

My PHP code goes like this.

$dbf = fopen('BRA.dbf','rb');
fread($dbf,10); // jumps over the first 10 bytes
$dbfRecSize = unpack('v',fread($dbf,2))[1]; // 'v' = little endian 16 bits: 00d1 = d1(16) = 209
fread($dbf,17); // jumps over a few more bytes
$dbfLangID = ord(fread($dbf,1)); // language driver ID
if ($dbfLangID == 0x57) {
    echo "Language: 0x57 (ISO-8859-1)\n";
} else {
    echo "Language: $dbfLangID;\n";
}

The code above outputs "Language: 0x57 (ISO-8859-1)", which means the "57" close to the end of the od output is being read with the ord(fread($dbf,1)); command.

Strange thing is that I've read 10+2+17 = 29 bytes from the file, so the next byte should be "00", or not (right after the 0x57)? $dbfRecSize is 209, which means my logic is correct in the first two reads. Why isn't it in the following reads?

What am I misunderstanding here?

Upvotes: 0

Views: 282

Answers (1)

Rodrigo
Rodrigo

Reputation: 5129

The error is that I was confusing od command with debug from DOS...

od -x prints bytes with the order reversed every two bytes (too confusing to me).

0000000 7703 1e07 001b 0000 00a1 00d1 0000 0000
0000020 0000 0000 0000 0000 0000 0000 5700 0000

od -t x1 prints each byte once and separated (harder to count/read in the middle of the line).

0000000 03 77 07 1e 1b 00 00 00 a1 00 d1 00 00 00 00 00
0000020 00 00 00 00 00 00 00 00 00 00 00 00 00 57 00 00

Wonder if is there an option to print bytes two by two (in hexadecimal), without reversing their orders?

Upvotes: 1

Related Questions