'Failed to fetch SPC data.']); exit; } // Parse the KML content $xml = simplexml_load_string($kml_content, "SimpleXMLElement", LIBXML_NOCDATA); if ($xml === false) { echo json_encode(['error' => 'Failed to parse KML data.']); exit; } // Register the KML namespace $xml->registerXPathNamespace('kml', 'http://www.opengis.net/kml/2.2'); $features = []; // Find all Placemarks in the KML foreach ($xml->xpath('//kml:Placemark') as $placemark) { $placemark->registerXPathNamespace('kml', 'http://www.opengis.net/kml/2.2'); $name = (string)$placemark->name; // Look for Polygon $polygon = $placemark->xpath('.//kml:Polygon'); if ($polygon && isset($polygon[0]->outerBoundaryIs->LinearRing->coordinates)) { $coordinates_str = (string)$polygon[0]->outerBoundaryIs->LinearRing->coordinates; $coordinates = parse_coordinates($coordinates_str); if (!empty($coordinates)) { $features[] = [ 'name' => $name, 'type' => 'Polygon', 'coordinates' => $coordinates ]; } } } echo json_encode($features); function parse_coordinates($coordinates_str) { $coords = []; $pairs = explode(' ', trim($coordinates_str)); foreach ($pairs as $pair) { $parts = explode(',', $pair); if (count($parts) >= 2) { $lon = floatval($parts[0]); $lat = floatval($parts[1]); // Ensure coordinates are valid if (is_finite($lat) && is_finite($lon)) { $coords[] = $lon; $coords[] = $lat; } } } return $coords; } ?>