基于SVG标签生成州与地区数组的PHP/JS实现需求
Solution: Extract Region-State Mappings from US SVG Map with PHP & JavaScript
Hey Jake, let's break down how to turn your SVG map into that region-keyed state dictionary you need. We'll cover both PHP (server-side) and JavaScript (client-side) approaches since you mentioned using both languages.
PHP Implementation (Server-Side)
Since you're already loading the SVG with file_get_contents(), we'll use PHP's DOM extension to parse the SVG (which is just XML under the hood) and build our mapping.
Step-by-Step Code
<?php // Load your SVG content $svgContent = file_get_contents('usa.svg'); // Initialize DOM parser, suppress XML warnings (common with SVGs) $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadXML($svgContent); libxml_clear_errors(); // Target path elements (adjust to 'g' if your states are grouped in <g> tags) $elements = $dom->getElementsByTagName('path'); $regionStateMap = []; foreach ($elements as $element) { // Extract region from class, state from id (swap these if your SVG uses reverse attributes) $region = $element->getAttribute('class'); $state = $element->getAttribute('id'); // Skip elements missing either attribute if (empty($region) || empty($state)) continue; // Initialize region array if it doesn't exist if (!isset($regionStateMap[$region])) { $regionStateMap[$region] = []; } // Add state to the region's list $regionStateMap[$region][] = $state; } // Output as formatted JSON header('Content-Type: application/json'); echo json_encode($regionStateMap, JSON_PRETTY_PRINT); ?>
Key Notes for PHP
- Adjust Element Type: If your SVG uses
<g>groups instead of<path>for states, changegetElementsByTagName('path')togetElementsByTagName('g'). - Attribute Swap: If your SVG uses
idfor regions andclassfor states, just swap the$regionand$stateassignments. - Namespace Handling: If your SVG has an
xmlnsattribute, use DOMXPath for more reliable element selection:$xpath = new DOMXPath($dom); $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg'); $elements = $xpath->query('//svg:path[@class and @id]');
JavaScript Implementation (Client-Side)
If you need to parse the SVG directly in the browser, here are two common scenarios:
Scenario 1: SVG is Embedded in the Page
If your SVG is already on the page (e.g., <svg id="usa-map">...</svg>):
const svg = document.getElementById('usa-map'); const regionStateMap = {}; // Target all path elements with both class and id attributes const stateElements = svg.querySelectorAll('path[class][id]'); stateElements.forEach(el => { const region = el.getAttribute('class'); const state = el.getAttribute('id'); if (!regionStateMap[region]) { regionStateMap[region] = []; } regionStateMap[region].push(state); }); // Use the map (log to console or integrate into your app) console.log(JSON.stringify(regionStateMap, null, 2));
Scenario 2: Load SVG via Fetch
If you need to load the SVG file dynamically:
fetch('usa.svg') .then(res => res.text()) .then(svgText => { // Create a temporary container to parse the SVG const tempContainer = document.createElement('div'); tempContainer.innerHTML = svgText; const svg = tempContainer.querySelector('svg'); const regionStateMap = {}; const stateElements = svg.querySelectorAll('path[class][id]'); stateElements.forEach(el => { const region = el.getAttribute('class'); const state = el.getAttribute('id'); if (!regionStateMap[region]) { regionStateMap[region] = []; } regionStateMap[region].push(state); }); console.log(regionStateMap); }) .catch(err => console.error('Failed to load SVG:', err));
Key Notes for JavaScript
- Attribute Flexibility: If your SVG uses custom attributes (like
data-regioninstead ofclass), updategetAttribute('class')to match your SVG's structure. - Deduplication: If a state accidentally appears in multiple regions, use a
Setto avoid duplicates:regionStateMap[region] = [...new Set([...regionStateMap[region], state])];
内容的提问来源于stack exchange,提问作者Jake Baum
相关产品推荐
相关产品推荐

