NCX001
NCX001

Reputation: 117

Dealing with XML in PHP

I'm currently working a project that has me working with XML a lot. I have to take an XML response and decrypt each text node and then do various tasks with the data. The problem I'm having is taking the response and processing each text node. Originally I was using the XMLToArray library, and that worked fine I would change the XML into an array and then loop through the array and decrypt the values. However some of the XML response I'm dealing with have repeated tags and the XMLToArray library will only return the last values.

Is there a good way that I can take an XML response and process all the text nodes and easily putting the values into an array that has a similar structure to the response?

Thanks in advance.

Upvotes: 1

Views: 252

Answers (4)

binaryLV
binaryLV

Reputation: 9122

I would use SimpleXML.

Here's a small example of using it. It loads and parses XML from http://www.w3schools.com/xml/plant_catalog.xml and then outputs values of "COMMON" and "PRICE" tags of each "PLANT" tag.

$xml = simplexml_load_file('http://www.w3schools.com/xml/plant_catalog.xml');
foreach ( $xml->PLANT as $plantNode ) {
    echo $plantNode->COMMON, ' - ', $plantNode->PRICE, "\n";
}

If you have any problems with adapting it to your needs, just give an example of your XML so that we can help with it.

Upvotes: 4

Álvaro González
Álvaro González

Reputation: 146660

All those XML to array libraries are a remain of the times where PHP 4 would force you to write your own XML parser almost from scratch. In recent PHP versions you have a good set of XML libraries that do the hard job. I particularly recommend SimpleXML (for small files) and XMLReader (for large files). If you still find them complicate, you can try phpQuery.

Upvotes: 1

Dave Kiss
Dave Kiss

Reputation: 10495

Check out SimpleXML, it may offer a bit more for what you are looking for.

Upvotes: 0

boug
boug

Reputation: 1887

You might want to give SimpleXML a try. Plus it comes by default in php so you dont need to install

Upvotes: 0

Related Questions