How is it possible to modify the whole body part of an xml document loaded in php via simplexml?

末鹿安然 提交于 2019-12-12 05:27:18

问题


Assume the following xml document

<technicaldata template="123">

<name>
<![CDATA[Blub1]]>
</name>


<numbers>

<![CDATA[1
2
3
4
5]]>
</numbers>

<shortinfo>

<![CDATA[ha ha ha ha ha ha ha ha.]]>
</shortinfo>

<detailedinfo>

<![CDATA[hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi
hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi
hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi]]>
</detailedinfo>


</technicaldata>

Now I load the file via simplexml;

$data='test.xml';
$inhalt = simplexml_load_file($datei);

But now $inhalt is an object where I can't use e.g. str_ireplace(string remove, string add,$inhalt); So if I e.g. want to replace something I need to go into every body part of the xml document in order to be able to replace it;

So I do this:

$name = $inhalt->name;
$name = str_ireplace(string remove, string add,$name);

$numbers = $inhalt ->numbers;
$numbers = str_ireplace(string remove, string add,$numbers);

$shortinfo=$inhalt ->shortinfo;
str_ireplace(string remove, string add,$shortinfo);

$detailedinfo=$inhalt ->detailedinfo;
str_ireplace(string remove, string add,$detailedinfo);

and so on;

So do you have any idea how I can replace something for the whole body part and not just parts of it? So some version of:

$inhalt = str_ireplace(string remove, string add,$inhalt);

which doesnt't work in this case?

Sorry, I know it sounds totally easy and stupid but I'm a bloody beginner;

Many thanks!! :)


回答1:


you could loop through all the children of your xml object like this:

foreach ($inhalt->children() as $child) {
    $child= str_ireplace(string remove, string add,$child);
}

hope it helps




回答2:


This is easier in DOM because you can address and modify the text nodes (including CDATA sections) directly:

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('/technicaldata/*//text()') as $textNode) {
  $textNode->data = str_replace(['hi', 'ha'], ['foo', 'bar'], $textNode->data);
}

echo $document->saveXml();

The Xpath expression

In the technicaldata document element fetch any element node ...

/technicaldata/*

... fetch text node (simple text or cdata sections) inside them:

/technicaldata/*//text()



来源:https://stackoverflow.com/questions/33569274/how-is-it-possible-to-modify-the-whole-body-part-of-an-xml-document-loaded-in-ph

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!