2014-04-03 69 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> 
相關問題