开发者

PHP use dom to import simple XML element with prefix

$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:l开发者_C百科oc', '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);
}

and I'm trying to get it to take this 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>

and make it look like this:

<?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>

But when ever I try to do the second insertNode() I get this error:

Warning: dom_import_simplexml(): Invalid Nodetype to import in /volume1/web/truefoodlooks/test/index.php on line 47

How can I fix this?


You cannot pass complex object syntax as string. I made some modifications in your code to solve your problem, but its not a great approach:

        $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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜