samedi 1 août 2015

How can I extract all text from XML data using PHP (i.e. SimpleXmlElement)?

Here's my XML data:

$data = '<title>Report of the <org reg="International Foo and Bar Conference, 5th">Fifth International Foo and Bar Conference</org>, <org>Foobar Hall</org>, London, July 14 to 16, 1908.</title>'; 

I can load it:

$xml = simplexml_load_string( $data ); 
print_r( $xml );

This returns: SimpleXMLElement Object ( [org] => Array ( [0] => Fifth International Foo and Bar Conference [1] => Foobar Hall ) ).

But now I can try to get it in a string again:

$flat = (string) $xml;
print_r( $flat ); 

And this is what I see:

Report of the , , London, July 14 to 16, 1908.

But I'd rather it was this:

Report of the Fifth International Foo and Bar Conference, Foobar Hall, London, July 14 to 16, 1908.

Is there an easy way to do that with PHP, without explicitly recursing through every node? That's to say, is there a way to just flatten the XML and extract all the text from it, regardless of tags?

Aucun commentaire:

Enregistrer un commentaire