I am trying to read credentials from xml and initialize to private variables using php.
<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
<host>localhost</host>
<username>Jani</username>
<password>1234r</password>
</config>
I am using following class and constructor to initialize variables.
<?php
class Admin {
public $host = "";
private $username;
private $password;
private $table;
private $crendentials = array();
public function __construct() {
$xml = simplexml_load_file("config.xml");
foreach ($this->crendentials as $key => $value) {
if ($key == $this->host) {
$this->host = $value;
} elseif ($key == $this->username) {
$this->username = $value;
} elseif ($key == $this->password) {
$this->password = $value;
}
}
foreach ($xml->children() as $child) {
$this->crendentials[$child->getName()] = $child;
}
}
public function getHost() {
print_r($this->crendentials);
echo $this->host;
echo $this->username;
echo $this->password;
}
}
$obj = new Admin;
$obj->getHost();
?>
It’s not initializing variables. Is there a good way to load credentials, other than that? I am creating a cms. I did some research like using ini file. But I think xml is most easiest.
I see two problems:
$this->crendentialsis an empty array. So your firstforeachnever runs.$xml->children(), the secondforeachlikely does nothing.Leaving aside that you’re loading credentials from an XML file, I’d suggest condensing the two
foreachloops into one. Simply looping over the XML keys and assigning them to their respective class properties. That is to say drop$this->crendentials.