Read xml data in php

Home / PHP / Read xml data in php

PHP: Hypertext Preprocessor programming language, a popular dynamic web page scripting language, features the built-in SimpleXML extension, which simplifies reading and using XML in your PHP scripts. Read an RSS feed, XML office documents, or your own custom XML document.

Here we use SimpleXML library, which is not only the best for converting string to XML object but is also built into PHP core so there is no need to install it. Once you have the URL of the XML feed that you are going to use, you need to have PHP load the contents of the feed into a string variable. Using file_get_contents, you could fetch the XML file like so:

How to Read an XML File With PHP

<?php	
$xmlStr = file_get_contents('http://www.youdomain.com/feeds/news.xml');
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
echo "<pre>";print_r($arrXml);echo "</pre>";
?>

Here is the function to convert XMLObject into Array

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();
   
    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }
   
    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Other way to read XML data with cURL

cURL to read RSS feed XML+PHP

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://www.youdomain.com/feeds/news.xml');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
?>

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *