2014-04-03 68 views
2

我试图在添加页面时自动更新网站地图。我正在定义包含我需要的子名称的var,其中包含冒号字符。 PHP或XML将冒号和单词移到其左侧或右侧。我如何将冒号保留在子元素名称中?使用PHP在XML子元素名称中包含冒号

我使用这个:

<?php 
$imagechild = 'image:image'; 
$imageloc = 'image:loc'; 

$xml=simplexml_load_file("sitemap.xml"); 

$map = $xml->addChild('url'); 
    $map->addChild('loc', "http:/some website".$page_path); 

$img = $map->addChild($imagechild); 
    $img->addChild($imageloc, $img_link); 

    $xml->saveXML('sitemap.xml'); 
?> 

我得到这个:

 <url> 
     <loc>web url</loc> 
     <image> 
      <loc>image url</loc> 
     </image> 
     </url> 

我需要这个

 <url> 
     <loc>web url</loc> 
     <image:image> 
      <loc>image url</loc> 
     </image:image> 
     </url> 

预先感谢您!

回答

3

如果一个元素名称包含:那么:之前的部分是命名空间前缀。如果您使用的是名称空间前缀,那么您需要在文档中的某处定义名称空间。

检查的SimpleXmlElement::addChild()手册。你需要通过命名空间URI作为第三个元素,以使其工作:

$img = $map->addChild($imagechild, '', 'http://your.namspace.uri/path'); 

我会鼓励你使用DOMDocument类有利于simple_xml延伸。它可以更好地处理名称空间。检查这个例子:

假设你有这样的XML:

<?xml version="1.0"?> 
<map> 
</map> 

这PHP代码:

$doc = new DOMDocument(); 
$doc->load("sitemap.xml"); 

$map = $doc->documentElement; 

// Define the xmlns "image" in the root element 
$attr = $doc->createAttribute('xmlns:image'); 
$attr->nodeValue = 'http://your.namespace.uri/path'; 
$map->setAttributeNode($attr); 

// Create new elements 
$loc = $doc->createElement('loc', 'your location comes here'); 
$image = $doc->createElement('image:image'); 
$imageloc = $doc->createElement('loc', 'your image location comes here'); 

// Add them to the tree 
$map->appendChild($loc); 
$image->appendChild($imageloc); 
$map->appendChild($image); 

// Save to file 
file_put_contents('sitemap.xml', $doc->saveXML()); 

你会得到这样的输出:

<?xml version="1.0"?> 
<map xmlns:image="http://your.namespace.uri/path"> 
    <loc>your location comes here</loc> 
    <image:image> 
    <loc>your image location comes here</loc> 
    </image:image> 
</map> 
相关问题