Ben
Ben

Reputation: 25807

How to deleted an element inside XML string?

How can the <title> element be deleted inside this XML string?

$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>.....';

Thanks

Upvotes: 1

Views: 503

Answers (2)

ajreal
ajreal

Reputation: 47321

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());

Upvotes: 7

Mike Clark
Mike Clark

Reputation: 10136

If you are working with unknown input data, or with production code, you should use an XML parser.

If you're working in test environment and the input data is known:

$output = preg_replace('%<title>[^<]*</title>%', '', $input);

If you need to allow for attributes on the tag, I suggest using a real XML parser, for maximum reliability and minimum chance of error.

Upvotes: 2

Related Questions