$loopc = 0;
foreach( $xmls->url as $url ) {
$num = $xmls->count();
if ( $loopc <= $num ) {
insertNode($xmls, 'url['.$loopc.']', 'image:image', NULL);
insertNode($xmls, 'url['.$loopc.']->image', 'image:loc', 'urldata');
$loopc = $loopc+1;
} else {
break;
}
}
echo $xmls->asXML();
function insertNode(SimpleXMLElement $xml, $path, $qname, $val) {
eval('$cur = $xml->'.$path.';');
$sd = dom_import_simplexml($cur);
$newNode = $sd->ownerDocument->createElement($qname, $val);
$newNode = $sd->appendChild($newNode);
return simplexml_import_dom($newNode);
}
我试图让它采用这个XML:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.sitemaps.org/schemas/sitemap-image/1.1" xmlns:video="http://www.sitemaps.org/schemas/sitemap-video/1.1">
<url>
<loc>http://truefoodlooks.comcompare.php?id=49</loc>
</url>
</urlset>
并使它看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.sitemaps.org/schemas/sitemap-image/1.1" xmlns:video="http://www.sitemaps.org/schemas/sitemap-video/1.1">
<url>
<loc>http://truefoodlooks.comcompare.php?id=49</loc>
<image:image>
<image:loc>urldata</image:loc>
</image:image>
</url>
</urlset>
但是当我尝试做第二次insertNode()
时,我收到了这个错误:
警告:dom_import_simplexml():要在第47行的/volume1/web/truefoodlooks/test/index.php中导入的无效节点类型
我该如何解决这个问题?
答案 0 :(得分:0)
您不能将复杂对象语法作为字符串传递。我对您的代码进行了一些修改以解决您的问题,但这不是一个好方法:
$loopc = 0;
foreach( $xmls->url as $url ) {
$num = $xmls->count();
if ( $loopc <= $num ) {
insertNode($xmls, 'url',$loopc,'image:image', NULL);
insertNode($xmls->url[$loopc], 'image:image',NULL, 'image:loc', 'urldata');
$loopc = $loopc+1;
} else {
break;
}
}
echo $xmls->asXML();
function insertNode(SimpleXMLElement $xml, $pathName, $pathIndex, $qname, $val) {
if(!is_null($pathIndex))
{
$cur = $xml->{$pathName}[$pathIndex];
}
else{
$cur = $xml->{$pathName};
}
$sd = dom_import_simplexml($cur);
$newNode = $sd->ownerDocument->createElement($qname, $val);
$newNode = $sd->appendChild($newNode);
return simplexml_import_dom($newNode);
}