How can I parse a complex XML with PHP and CDATA?

How Can I fetch and parse XML from an other website using PHP?

  • UPDATE: I have changed this question a bit from what I learned and restructured it here: __________________ Previously: I am creating a website in php. I need to add a search that uses an api from another website. I know how to construct the url for the api by using the search term entered by a user. But how do I fetch the xml with php using ajax and then parse the xml to display all the results within my website?

  • Answer:

    AJAX is a client-side technique, you cannot do it with PHP. However, you can fetch an URL using file_get_contents() function. Example: $search = some_escaping_func($user_input); $uri = 'http://www.other-site.com/api.xml?q='.$search; $response = file_get_contents($uri); $items_names = parse_xml($response); // output the result echo '<ul>'; foreach ($items_names as $name) { echo '<li>'.htmlspecialchars($name).'</li>'; } echo '</ul>'; Where parse_xml() is defined with the following code: function parse_xml($xml_str) { $items = array(); $xml_doc = new SimpleXMLElement($xml_str); foreach ($xml_doc->item as $item) { $items []= $item->name; } return $items; } This example assumes that the API response is something like this: <?xml version='1.0' standalone='yes'?> <items> <item> <name>Foo</name> </item> <item> <name>Bar</name> </item> </items> file_get_contents function: http://php.net/manual/en/function.file-get-contents.php SimpleXMLElement examples: http://www.php.net/manual/en/simplexml.examples-basic.php

Baptiste Fontaine at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.