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>
精彩评论