| 1 | = MS4W Version 5.x Query From .MAP File Sample = |
| 2 | |
| 3 | original source: https://gist.github.com/andrewteg/81b8d45948d67003f5f1170e51d66e61 |
| 4 | |
| 5 | {{{ |
| 6 | #!php |
| 7 | <html><head><title>query sample</title></head><body><PRE> |
| 8 | <?php |
| 9 | |
| 10 | // sample filter strings to search on... 'name' is field in Attribute Table for Layer |
| 11 | $filter_string = '("[name]" == "Canada")'; //exact (use ==) - case-sensitive |
| 12 | //$filter_string = '("[name]" ~* "^ca.*")'; //starts Ga (^ for starting) not case-sensitive |
| 13 | //$filter_string = '("[name]" ~* ".*CA.*")'; //like Ga (.* maybe not needed?!?) not case-sensitive |
| 14 | |
| 15 | $map = new mapObj("/ms4w/apps/local-demo/local.map"); |
| 16 | |
| 17 | $layer = $map->getLayer(1); //second layer in mapfile |
| 18 | $layer->setFilter($filter_string); //filter results |
| 19 | $layer->template = true; //for historical reasons, the query attribute must be non-NULL for a layer to be queryable RE: https://www.mapserver.org/mapscript/mapscript.html#layerobj-attributes |
| 20 | |
| 21 | $ext = $layer->getExtent(); |
| 22 | $query = $layer->queryByRect($map, $ext); //must query before getting $layer numitems |
| 23 | $numResults = $layer->getNumResults(); |
| 24 | |
| 25 | $layername = $layer->name; |
| 26 | $layeritems = $layer->numitems; //count of items in attribute table |
| 27 | //echo 'Layer '.$layername.' has '.$layeritems.' items<br>'; |
| 28 | for ($x=0;$x<$layeritems;$x++) { |
| 29 | $layer_headers[$x] = $layer->getItem($x); //for the layer, this gets the attribute field names |
| 30 | } |
| 31 | //print_r($layer_headers); |
| 32 | |
| 33 | if($query == MS_SUCCESS) { |
| 34 | echo 'Query has '.$layer->getNumResults().' Results:<br>'; |
| 35 | if($layer->getNumResults()>0) { |
| 36 | for ($i=0; $i < $layer->getNumResults(); $i++) { |
| 37 | $result = $layer->getResult($i); //print_r($result); |
| 38 | if($result === FALSE) { |
| 39 | error_log('No result '.$i); |
| 40 | } else { |
| 41 | $shape = $layer->getShape($result); //print_r($shape); |
| 42 | //echo ("#$i OBJECTID = ".$shape->values['OBJECTID'].'<br>'); //ms4w 3.x |
| 43 | //echo 'vals='.$shape->numvalues; |
| 44 | echo ("#$i OBJECTID = ".$shape->getValue(0)); //ms4w 4.x |
| 45 | $vals = array(); |
| 46 | echo '<blockquote>'; |
| 47 | for ($x=0;$x<$shape->numvalues;$x++) { |
| 48 | //echo $x.'='.$shape->getValue($x).'<br>'; |
| 49 | $vals[$layer_headers[$x]] = $shape->getValue($x); |
| 50 | } |
| 51 | print_r($vals); |
| 52 | //echo 'WKT='.$shape->toWKT().'<br>'; |
| 53 | print_r($shape->values); |
| 54 | echo '</blockquote>'; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | } else { |
| 59 | echo('Query Returned No Results'); |
| 60 | } |
| 61 | echo '<hr>END<hr>'; ?> |
| 62 | </PRE></body></html> |
| 63 | }}} |