我是第一次尝试构建xml站点地图,所以我暂时陷入困境。我有输出但现在我必须将数据添加到xml文件。我已经提供了关于我现在有多远的例子,我正在努力循环所有必须添加到xml输出文件的数据。
更新:现在正在运行,欢迎任何改进!
class XmlForSite{
static function outputXml(){
$xmlSitemap = 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>');
var smap = self::buildXml( $xmlSitemap );
$xml = $smap->asXml();
$document = new \DOMDocument('1.0','UTF-8');
$document->formatOutput = true;
$document->loadXml($xmlSitemap->asXml());
$xml = $document->saveXml();
// final output, this will be used on a page somewhere
return $xml;
}
public function buildXml(){
// just an example, orginal array is bigger ;-)
$files = array('lang'=>'url');
foreach($files as $key => $value){
// working but this must be in an array as output
$url = $xmlSitemap->addChild('url');
$url->addChild('loc', 'www' );
$url->addChild('lastmod', 'mod' );
$url->addChild('changefreq', 'daily');
$url->addChild('priority', '1.0');
//example on how i want to output it
$output[] = '<url>
<loc>' .$value. '</loc>
<xhtml:link rel="alternate" hreflang="' .$key. '" href="' .$value. '"/>
</url>';
}
return $xml;
}
}
答案 0 :(得分:-1)
直接从PHP手册中获取 - 应该有助于创建节点和添加属性。我可以声称代码没有信用....
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');
$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');
$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');
echo $sxe->asXML();