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
Related Q & A:
- How can I allow user to create posts in website using ASP.NET?Best solution by Programmers
- How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?Best solution by Arduino
- How can I detect changes in XML?Best solution by Stack Overflow
- How can I extract data of an external XML to PHP?Best solution by Stack Overflow
- How can I put pictures into my e-mail instead of using attachments?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.