php在循环中创建xml CDATA


php create xml CDATA on loop

想要进行循环并解析XML CDATA我的XML

<?xml version="1.0"?>
<photos>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
    </photo>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
    </photo>
</photos>

我的代码

for ($x = 1; $x <= 10; $x++) {
    $dom=new DOMDocument();
    $xml='images.xml';
    $dom->load($xml);
    $xp = new DomXPath($dom);
    //$item_content = $xp->query("//*[@id = $x]");
    foreach ($dom->getElementsByTagName('photos') as $item) {
        $cdata=$dom->createCDATASection('<head>test'.$x.'</head><body></body>');
        $item->getElementsByTagName('photo')->item(0)->appendChild($cdata);
    }
    $dom->save($xml);
}

但是的结果

    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
    <![CDATA[<head>test1</head><body></body><head>test2</head><body></body><head>test3</head><body></body>
    <head>test4</head><body></body><head>test5</head><body></body>
<head>test6</head><body></body><head>test7</head>
    <body></body><head>test8</head><body></body><head>test9</head><body></body>]]><![CDATA[<head>test10</head><body>
    </body>]]></photo>
    <photo image="images/2.jpg" url="http://http://LINKHERE" target="_blank" id="2">
    </photo>

我想要这个

<photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
<![CDATA[<head>test1</head><body></body>]]></photo>
<photo image="images/2.jpg" url="http://http://LINKHERE" target="_blank" id="2">
<![CDATA[<head>test2</head><body></body>]]></photo>

我想按id循环我试了很多次,但没有办法,我想我的循环有问题这里需要一些帮助

您希望在每个photo元素上附加CData,因此应该循环通过photo而不是photos,例如:

$raw = <<<XML
<photos>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
    </photo>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
    </photo>
</photos>
XML;
$dom = new DOMDocument();
$dom->loadXML($raw);
$x = 1;
foreach ($dom->getElementsByTagName('photo') as $item) {
    $cdata=$dom->createCDATASection('<head>test'.$x.'</head><body></body>');
    $item->appendChild($cdata);
    $x++;
}
echo $dom->saveXML($xml);

eval.in demo

输出:

<?xml version="1.0"?>
<photos>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="1">
    <![CDATA[<head>test1</head><body></body>]]></photo>
    <photo image="images/1.jpg" url="http://LINKHERE" target="_blank" id="2">
    <![CDATA[<head>test2</head><body></body>]]></photo>
</photos>

试试这个代码

<?php
    $dom=new DOMDocument();
$xml='images.xml';
    $dom->load($xml);
    $xp = new DomXPath($dom);
$i = 0;
    foreach ($dom->getElementsByTagName('photo') as $item) {
        $cdata=$dom->createCDATASection('<head>test'.($i+1).'</head><body></body>');
        $item->appendChild($cdata);
$i ++;
    }
    $dom->save($xml);