想要循环和解析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移动循环 我尝试了很多次,但没办法,我觉得我的循环有问题 需要一些帮助
答案 0 :(得分:0)
您希望在每个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>
答案 1 :(得分:0)
试试此代码
<?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);