You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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, change getElementsByTagName('path') to getElementsByTagName('g').
  • Attribute Swap: If your SVG uses id for regions and class for states, just swap the $region and $state assignments.
  • Namespace Handling: If your SVG has an xmlns attribute, 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-region instead of class), update getAttribute('class') to match your SVG's structure.
  • Deduplication: If a state accidentally appears in multiple regions, use a Set to avoid duplicates:
    regionStateMap[region] = [...new Set([...regionStateMap[region], state])];
    

内容的提问来源于stack exchange,提问作者Jake Baum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:46:09