How to Read External XML File with PHP

How to Read External XML File with PHP

Today it is fashionable to have a personal or professional blog with different objectives which can be connected externally in various ways.

In this article we will explain one of the ways to read an external XML file with PHP. In the example we will illustrate let’s see how externally connected to the blog of lucidkit.

We will add to our page the following PHP function:

ReadXml function ($ filename, $ limit) {
    $ File_XML = file_get_contents ($ filename);
    if (empty ($ file_XML))
        die ( "could not connect");

    preg_match_all ( "| <item> (*) </ item> | them." $ file_XML, $ items);

    $ Nodes = array ();

    foreach ($ items [1] as $ key => $ item) {
        preg_match ( "| <title> (*) </ title> | s." $ item, $ title);
        preg_match ( "| <link> (*) </ link> | s." $ item, $ link);
        preg_match ( "| <description> (*) </ description> | s." $ item, $ description);

        $ Nodes [$ key] [ 'title'] = $ title [1];
        $ Nodes [$ key] [ 'link'] = $ link [1];
        $ Nodes [$ key] [ 'description'] = $ description [1];
    }

    for ($ i = 0; $ i <$ limit; $ i ++) {
        echo '<a href="'. $nodes[$i]['link'].'" target="_blank">'. $ Nodes [$ i] [ 'title']. '</a> <br>';
        echo $ nodes [$ i] [ 'description'] "<br>.";
    }
    $ Xml_file = "";
}

This function receives the file or external url that contain an XML reading (blog feed WordPress) and the number of posts or entries to display as parameters.

Now we just need to see how to call this function, for example:

ReadXml ( "http://lucidkit.com/blog/feed/", 6);
Lucid Kit

Related Posts
Leave a reply
Captcha Click on image to update the captcha .