在php中的另一个节点中附加xml节点
问题描述:
I want to insert different nodes inside the node. but i dont know how to do it dynamically
I have this xml file:
<?xml version='1.0' encoding='UTF-8'?>
<article artId="4686453" artName="UHOPI20190218-012A" Author="" Comment="" PubDate="2019-02-18" Section="country">
<head>
<headline>this is the title </headline>
<summary>
autor name @twitter
</summary>
</head>
<body>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer venenatis eleifend dui, at egestas sapien lobortis viverra.
<!-- insert pullquotes here -->
</body>
<pullquote title="" catsList="" summary="" notes="" sectionColor="" sectionHead="">
Lorem ipsum dolor sit amet
<summary xml:space="preserve">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</summary>
</pullquote>
<pullquote title="" catsList="" summary="" notes="" sectionColor="" sectionHead="">
<headline xml:space="preserve">Some text</headline>
<summary xml:space="preserve">Some text</summary>
<summary xml:space="preserve">Some text</summary>
</pullquote>
</article>
I try this...but it doesnt work
$xml = simplexml_load_file("files/test2.xml");
$body = $xml->body;
$pull1 = $xml->pullquote[0];
$body->addChild($pull1);
I want to insert every node inside the node how can i do this?
答
This is my solution:
if($xmlData->body){
$xmlIterator = new SimpleXMLIterator($xmlData->body->asXML());
$xmlIterator->rewind();
$txtBody = "";
for($i=0; $i < ($xmlIterator->count()); $i++){
$txtBody .= (trim($xmlIterator->current()) <> '') ? "<p>".trim($xmlIterator->current())."</p>" : "";
$xmlIterator->next();
}
#INSERT PULLQUOTE
foreach($xmlData->pullquote as $pull){
$txtBody .= $pull;
foreach ($pull->children() as $child){
$txtBody .= $child;
}
}
$data = $txtBody;
}