如何在此XML字符串中删除<title>
元素?
$input=
'<items>dfd jdh flkdjf
<title>My Test Title
</title>....
<store>my store 1</store>
</items>.....';
$output=
'<items>dfd jdh flkdjf
....
<store>my store 1</store>
</items>.....';
由于
答案 0 :(得分:7)
Simplexml
$str = '<items>1<title>lalala</title><others>...</others></items>';
$xml = simplexml_load_string($str);
unset($xml->children()->title);
$output = str_replace("<?xml version=\"1.0\"?>\n", '', $xml->asXml());
答案 1 :(得分:2)
如果您使用的是未知输入数据或生产代码,应使用XML解析器。
如果您在测试环境中工作且输入数据已知:
$output = preg_replace('%<title>[^<]*</title>%', '', $input);
如果你需要在标签上允许属性,我建议使用真正的XML解析器,以获得最大的可靠性和最小的错误机会。