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

使用PHP SimpleXMLElement构建XML站点地图的两个技术问题

Fixing SimpleXMLElement Issues for Multilingual Sitemap Hreflang

Hey there! Let's work through these two SimpleXMLElement problems you're facing with your XML sitemap. Both issues tie into how SimpleXML handles XML namespaces, so let's break them down one by one.

When you call addChild('xhtml:link') directly, SimpleXML doesn't recognize the element as part of the xhtml namespace you declared in your <urlset>. To fix this, you need to pass the xhtml namespace URI as the third parameter to addChild(), using just link as the first parameter (the local element name).

SimpleXML will automatically map this URI to the xhtml prefix you already defined in your <urlset> attributes, resulting in the correct <xhtml:link> tag in your output.

Once the tag structure is correct, adding the rel, href, and hreflang attributes is straightforward with the addAttribute() method. Since these attributes don't belong to a specific namespace, you can call addAttribute() directly on the new link element.

Full Working Example

Here's how to put it all together, assuming your <urlset> is properly configured with the xhtml namespace:

// Initialize the sitemap with correct namespaces
$urlset = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"></urlset>');

// Assume $array contains your URL and language data
foreach ($array as $value) {
    // Create the parent <url> element (if not already done)
    $item = $urlset->addChild('url');
    // Add the main URL's <loc> element
    $item->addChild('loc', 'http://www.example.com/main-page-url');

    // Create the xhtml:link element with the correct namespace
    $alternateLink = $item->addChild('link', '', 'http://www.w3.org/1999/xhtml');
    
    // Add the required attributes
    $alternateLink->addAttribute('rel', 'alternate');
    $alternateLink->addAttribute('href', $value['url']); // Replace with your actual alternate URL
    $alternateLink->addAttribute('hreflang', $value['lang']); // Replace with your language code (e.g., 'de')
}

// Output the final XML
echo $urlset->asXML();

What This Produces

For each item in your array, you'll get the exact output you need inside the <url> element:

<xhtml:link href="http://www.example.com/path-to-file" hreflang="de" rel="alternate"/>

Key notes:

  • The second parameter in addChild('link', '', '...') is an empty string because <xhtml:link> is an empty element (no text content inside it).
  • Ensure your $value array holds the correct URL and language code for each alternate version of your page.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:05:58