使用PHP SimpleXMLElement构建XML站点地图的两个技术问题
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.
1. Why <xhtml:link> becomes <link> (and how to fix it)
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.
2. Adding hreflang attributes to <xhtml:link>
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
$valuearray holds the correct URL and language code for each alternate version of your page.
内容的提问来源于stack exchange,提问作者user759235

