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: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:PHP使用DOM導入簡單的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()
我得到這個錯誤:
Warning: dom_import_simplexml(): Invalid Nodetype to import in /volume1/web/truefoodlooks/test/index.php on line 47
我該如何解決這個問題?
你爲什麼說它不是一個好方法? – nat45928
因爲如果您想要SimpleXml返回,您不需要將SimpleXml轉換爲dom。只需使用$ simpleXMlElement-> addChild('node','value')即可。另一件事是,如果你想傳遞一個像'obj-> prop [0]'這樣的字符串的對象語法,你將不得不爲此構建一個解析器。 –