Skip navigation links

User Comments

Posted by Michael Newton on April 5 2006 7:03pm[Delete] [Edit]

To parse a WKB point in PHP, use the unpack function. It's similar to Perl's except that each format string has a label, and is separated from the next by a slash. The result is an associative array using those labels:

<?php
// $wkb is the value retrieved from MySQL using AsBinary(g)
$geometry unpack(corder/Ltype/dlatitude/dlongitude$wkb);
if (
$geometry['type'] == 1) {
    
$latitude $geometry['latitude'];
    
$longitude $geometry['longitude'];
}
?>

Posted by Nick Ananin on May 2 2008 8:47pm[Delete] [Edit]

You can also unpack a polygon or a collection (e.g. Multipolygon) as follows:

<?php

//Step 1 - get number of elements
$query1 "SELECT NumGeometries($geom)from ......" ;
$result1 mysql_query($query1);
$row1 mysql_fetch_row($result1);
$N $row1[0]; //number of polygons in the Multipolygon

//Step 2 - loop through each polygon 
$n=1;
while (
$n<=$N){
$query "SELECT AsBinary(GeometryN($geom,$n))from ....."
//returns a single POLYGON from a MULTIPOYGON
$result mysql_query($query);
if(
$result){  
  while (
$row mysql_fetch_array($resultMYSQL_NUM)) {
  
$geometry unpack("corder/Ltype/d*"$row[0]);
   
$i=2;
   while(
$i<count($geometry)){
   echo 
$geometry[$i]."<br>";
   
$i++;
   }
  }
 }
$n++;
}
?>


Hope it helps as it took me a little while to figure out how to extend the excellent unpack example given by Michael

Posted by Nathan V on September 2 2009 8:03pm[Delete] [Edit]

Adding to the two other examples, here is how to parse a LINESTRING:

<?php
// $wkb is the value retrieved from MySQL using AsBinary(g)
$geometry unpack(corder/Ltype/Llength/d*, $wkb);
if (
$geometry['type'] == 2) {
    for (
$i 1$i $geometry['length'] * 2$i += 2) {
        
$latitude $geometry[$i];
        
$longitude $geometry[$i+1];
    }
}
?>