开发者

Conditionally insert text node in XML document

开发者 https://www.devze.com 2023-02-18 04:47 出处:网络
The structure of my XML document is the following: <tr> <seg> <source>source_text</source>

The structure of my XML document is the following:

<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>

...
<seg>
<source>source_text</source>
</seg>

</tr>

Note that the dest element is not always present. I want to scan the file with PHP and insert a dest element (with some text) each time it's not present in a seg node.

Any help would be very appreciated开发者_如何学运维. Patrick


Try this, I tested this snippet, works for me:

$xml = '<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>
<seg>
<source>source_text</source>
</seg>
</tr>
';
$xmlObj = new SimpleXMLElement($xml);
foreach($xmlObj as $seg) {
    if(!$seg->dest) {
        $seg->dest = 'dest_text_inserted';
    }
}
echo $xmlObj->asXML();

It outputs what you need:

<?xml version="1.0"?>
<tr>
<seg>
<source>source_text</source>
<dest>dest_text</dest>
</seg>
<seg>
<source>source_text</source>
<dest>dest_text_inserted</dest></seg>
</tr>
0

精彩评论

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