Hi freinds, I am doing one task in that I have to get data from the link that i have. In that link the data is showing in xml format. How do I get the data using php
Thanks,
Hi freinds, I am doing one task in that I have to get data from the link that i have. In that link the data is showing in xml format. How do I get the data using php
Thanks,
Getting XML
data is no different than any other. You can use file_get_contents
as:
$xml = file_get_contents($url);
This will get the entire XML in a string $xml
which can later be parsed using say SimpleXML
Use SimpleXML, it's your best bet.
$xml = simplexml_load_file('test.xml');
You don't need to use file_get_contents first, as simplexml_load_file allows you to use full URLs and downloads the file for processing:
$xml = simplexml_load_file('http://www.example.com/test.xml');
$xml now contains an object of your XML file. It should be quite easy to work with, you can view the full structure by doing:
echo '<pre>'.print_r($xml, true).'</pre>';
It's important to think about your XML file's format. If it uses namespaces you'll have to do a little bit of tweaking to get the fields accessible, as these won't be available from the off.
You can use
DOMDocument::load
— Load XML from a file Example:
$doc = new DOMDocument();
$doc->load('http://example.com/data.xml');
echo $doc->saveXML();
You have to have allow_url_fopen
enabled in PHP.ini to load remote files. If not, you can see if cURL
is enabled on your webserver and fetch the file into a variable. Once the XML string is in the variable, you can use use DOMDocument::loadXML
to load the XML from a string.
To get elements from the data, you can use XPath queries or the other DOM API functions, e.g.
foreach( $doc->getElementsById('title') as $node) {
// do something with the $node
}
Virtually any of the common usecases when working with DOM have been answered before on StackOverflow. You should have no problem finding them when using the search function. Or browse some of my previous answers.