PHP – How to read a file from another server using FTP credentials?

I had a task to read file from another server. Obvious you would suggest file_get_contents or cURL for same. But those files was not accessible through URL. I have to read it using FTP server credentials, Initially I was trying with ftp_get and some other FTP functions. But it was download all files to my local server.

But finally I got the solution, here its….

    $filename = 'ftp://username:password@hostname/files/path/and/name.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    echo $contents;

I hope this would help you….


Create XML with PHP DOM

Usually while we are working on xml-based or on API, developers are need to create XML-encoded data structure on fly. Following sample code will explain you how to create XML using DOM

    header("Content-Type: text/plain");
    $doc = new DOMDocument('1.0', "UTF-8");
    $doc->formatOutput = true;
    $productList = $doc->createElement("ProductList");
    $doc->appendChild( $productList );

    $product = $doc->createElement( "Product" );

    $name = $doc->createElement( "name" );
    $product->appendChild( $name );

    $description = $doc->createElement("Description");
        $doc->createTextNode("This is test product description..!!!")
    $product->appendChild( $description );

    $price = $doc->createElement("Price");
    $product->appendChild( $price );

    $stockItems = $doc->createElement("StockItems");
        $stock = $doc->createElement("Stock");
            $name = $doc->createElement("Name");
            $stock->appendChild( $name );
            $onHandValue = $doc->createElement("OnHandValue");
            $stock->appendChild( $onHandValue );
        $stockItems->appendChild( $stock );
    $product->appendChild( $stockItems );
    $productList->appendChild( $product );
    echo $doc->saveXML();
    /* $doc->save("productlist.xml"); */

In above code,

– new DOMDocument(‘1.0’, “UTF-8”); will create DOM object for xml with argument 1.0 and encoding formate UTF-8

– createElement(“ProductList”), to create xml node “ProductList”

– $doc->appendChild( $productList ), append node to xml

– Create child node: to create child node we need to append child object node to its parent node object,  i.e. $product element to its parent element $productList. Here product is child of product list

– $doc->saveXML(), will create xml on fly and give the output on browser

Once we get the XML the way we want we can store get its value to string variable or it can also be store to server/system with given name and destination path as bellow,


You will get following output with this,

<?xml version="1.0" encoding="UTF-8"?>
  <Product product_id="13">
    <Description>This is test product description..!!!</Description>