Tuesday, January 22, 2013

Load PROPERTIES file in PHP like JAVA


A property file is basically consist of a data in key/value pair. In PHP is bit different than java. In java we used to create a .properties file and load using below code

Properties prop = new Properties();
prop.load(new FileInputStream("sample.properties"));

Now we will see equivalent code in PHP. In PHP instead of .properties it's .ini file and it is loaded using parse_ini_file() method. Please see the self explanatory code below

myProperties.ini

; This is a property file
; Comments start with ';', as in php.ini

id = 001
name = Alex
state = NY

loadProperties.php


<?php
$ini_array = parse_ini_file("myProperties.ini");
echo "Printing the array<br/>";
print_r($ini_array);

echo "<br/>";
echo "Get values by name";
echo "<br/>id = ".$ini_array['id'];
echo "<br/>name = ".$ini_array['name'];
echo "<br/>state = ".$ini_array['state'];
?>


Output



2 comments:

  1. Hi! In case you need to translate your .properties files, I suggest to have a look at https://poeditor.com/ which is a software localization management platform created to simplify the workflow.

    ReplyDelete