Here is one example of how to parse XML results using PHP.
To provide a specific example, I¡¯ve created a form and code that works with Amazon¡¯s web services. The code below displays a basic form, which queries Amazon, retrieves the XML data, parses the results, and displays them in a nicely formatted table.
Note that in order for this code to work, you will need to obtain your own Access Key ID, which you can easily do here.
- The complete script can be found here
- The XML sample file can be found here
We¡¯ll begin by a class containing the objects for our xml script:
Next, we need to identify the starting element and the ending element. Pay close attention the $element variable in both functions. This means that any tag in the XML document that we reference in this script must be typed in lowercase letters. So, if there¡¯s a tag
Here is where we create a new parser, tell it what to parse, and parse it.
NOTE: The array below should be filled in with the tags from the XML document you are parsing. Type 1 is a single field and type 2 is an array field.
NOTE: Change ¡®item¡¯ to whatever the closing tag is from your XML document.
In the event that one of the field_types (set in the OfferList function) is type 2, we¡¯ll tell it where to find the text:
Here is a function to sort the results. Note that, at least for Amazon, you can specify a parameter in the XML url to sort the results. But, if the url you¡¯ll be using doesn¡¯t have that feature, this is handy.
And this function display the results:
If errors were found with the user input, we¡¯ll show how to display the errors and we¡¯ll echo the form with the error messages:
And if the user hasn¡¯t done anything yet, we¡¯ll simply display the form:
I¡¯ve modified this code to include sort functionality and a feature that will display the XML results in a table with alternating row colors. Additionally, this code includes form validation. Much of the code has been borrowed from Programming PHP.
discuss this topic to forum
