Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to transform XML into PHP objects

Status
Not open for further replies.

vladibo

Programmer
Joined
Sep 14, 2003
Messages
161
Location
CA
How to transform XML into PHP objects? Can you give an example if its possible, please?

Thank you in advance.
 
i get email newsletters from and lo and behold it was this very topic...

here is the text from the newsletter

A PHP XML class for MySQL

I admit that I'm no PHP guru. However, after looking over the available information for PHP, I've determined that some functionality needs to be added for handling database connections and integrating XML. In order to do this, I thought I might create a class for handling the data connection to MySQL and providing XML output using the domxml functionality in PHP. Then, I can stick that class declaration in any of my PHP scripts and have the XML functionality available whenever I need it.

I imagine that one of the reasons why people use PHP is its pricetag: free. MySQL provides a free database solution for developers who want to add database functionality to their systems. The drawback is that these solutions are a bit more complicated to set up and administer.

The PHP version that I used for this article is PHP 4.3.4 for Win32, which you can download from The PHP Group. I also used MySQL 4.0.16 for Win32, which you can get from MySQL.com. Installation of MySQL was easy--you simply follow the instructions. PHP was a little more complicated.

On the download pages for PHP, there are two files: a ZIP archive and an installation file. Download both of these files because you need to add extensions that are located in the ZIP archive. Here are brief steps on how to go from there:


Install PHP from the install file.
Extract iconv.dll and place it in your Windows system folder.
Create a directory under your PHP installation folder (C:\PHP, by default) called "extensions."
Extract the php_domxml.dll file to this folder.
Locate the php.ini file in the Windows folder and open it with Notepad or some other text editor. Find "extensions_dir = " in this file and change the value to the complete path of the extensions folder from earlier.
Locate ";extension=php_domxml.dll" and remove the semi-colon from the front of the line.
Restart your Web server.

Now, create a PHP page called "test.php" in your Web directory and add the following code. (This code was tested on a Windows 2000 SP3 machine running IIS 5.0.)
Code:
<?php
$myxml = new CMySqlXML(&quot;localhost&quot;, &quot;test_user&quot;, &quot;password&quot;, &quot;test&quot;);
echo $myxml->run_sql_return_xml(&quot;SELECT * FROM users&quot;);

class CMySqlXML {
    var $host;
    var $user;
    var $password;
    var $db;

    function CMySqlXML($host, $user, $password, $db) {
        $this->host = $host;
        $this->user = $user;
        $this->password = $password;
        $this->db = $db;
    }
    
    function run_sql_return_xml($sql_string) {
        $connection = mysql_connect($this->host, $this->user, $this->password,
$this->db);
        mysql_select_db($this->db);
        $result = mysql_query($sql_string);
        $doc = domxml_open_mem(&quot;<root/>&quot;);
        while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $num_fields = mysql_num_fields($result);
            $row_element = $doc->create_element(mysql_field_table($result, 0));
            $doc_root = $doc->document_element();
            $row_element = $doc_root->append_child($row_element);
            for ($i = 0; $i < $num_fields; $i++) {
                $field_name = mysql_field_name($result, $i);
                $col_element = $doc->create_element($field_name);
                $col_element = $row_element->append_child($col_element);
                $text_node = $doc->create_text_node($row[$field_name]);
                $col_element->append_child($text_node);

            }
        }
        mysql_free_result($result);
        mysql_close($connection);

        return $doc->dump_mem(false);
    }
    
}
This example requires that you have a database named &quot;test&quot; on MySQL with a table called &quot;users.&quot; Also, you need to create a user for accessing the data on the test database. You can find steps on how to do this in the MySQL documentation.

If you examine the code, you'll see that I created a class called CMySqlXML. The CMySqlXML constructor function accepts four parameters: the hostname for MySQL, a valid username, a password, and a database name. The host, user, password, and db member variables are set with this constructor function.

The only method available is the run_sql_return_xml() function. It accepts a SQL query string parameter. When this function is executed, it creates a connection to the MySQL server and selects the database. The query string is executed, and the result is stored to the $result variable. A new DOMDocument object is created with the domxml_open_mem() function. Next, the code starts stepping through each record in the result set. For each record, a row element is added to the DOMDocument document element with the name of the table from the result set. Then, an element for each field is added to the row element using the field name for the element name. Finally, a text node is added to each field node with the text equal to the value stored in the field.

After each row is stepped through, the code frees up the result and closes the connection. The resulting DOMDocument XML is returned from the function.

At the start of the PHP page, you see where the CMySqlXML object is instantiated and the run_sql_return_xml() method is invoked. The return value from this method is returned to the client. The domxml functionality mimics the DOM specification, except the PHP function naming convention is followed.

If you'd like more information on DOM specifications, visit the W3C site. For more information on domxml, check out The PHP Group site, where you can download documentation in different formats.

Phillip Perkins is a contractor with Ajilon Consulting. His experience ranges from machine control and client/server to corporate intranet applications.


Bastien

Any one have a techie job in Toronto, I need to work...being laid off sucks!
 
Thank you Bastien, but this is not what I need I needed transformer from XML to PHP object. Any way this is the salution I foind, in case someone need it:
Code:
class XmlTransformer
{
	var $_parser;
	var $_file;
	var $_object = array();
	var $_depth = 0;
	var $_values = array();
	var $obj;
	var $_current;
	
	function XmlTransformer($file)
	{
		$this->_file = $file;
		$this->_parser = xml_parser_create();
	}
	function parse()
	{
		if (!($fp = fopen($this->_file, &quot;r&quot;))) {
		    die(&quot;could not open XML input&quot;);
		}
		while ($data = fread($fp, 4096)) {
		    $content .= $data;
		}
		xml_parser_set_option($this->_parser,XML_OPTION_CASE_FOLDING,0);
		xml_parser_set_option($this->_parser,XML_OPTION_SKIP_WHITE,1);
		xml_parse_into_struct($this->_parser,$content,$this->_values);
		xml_parser_free($this->_parser);
		$this->makeObject();
	}
	function makeObject(){
		$num = count($this->_values);
		$levels = array();
		$oldlevel = 0;
		$this->_current = array();
		for($i=0;$i<$num;$i++){
			$tag = $this->_values[$i][&quot;tag&quot;];
			$type = $this->_values[$i][&quot;type&quot;];
			$level = $this->_values[$i][&quot;level&quot;];

			$this->constructPath($tag,$level,$oldlevel);

			if($type==&quot;complete&quot;){
				$value = $this->_values[$i][&quot;value&quot;];
				eval(&quot;\$this->obj&quot;.$this->typeElements().&quot;='&quot;.$value.&quot;';\n&quot;);
			}
			$oldlevel = $level;
		}
	}
	function typeElements(){
		$result = &quot;&quot;;
		foreach($this->_current as $val){
			$result .= &quot;[\&quot;&quot;.$val.&quot;\&quot;]&quot;;
		}
		return $result;
	}
	function constructPath($tag,$level,$oldlevel){
		if($level > $oldlevel){
			array_push($this->_current,$tag);
		}else{
			$num = ($oldlevel - $level)+1;
			for($i=0;$i<$num;$i++){
				array_pop ($this->_current);
			}
			array_push($this->_current,$tag);
		}
	}
} 


$xt = new XmlTransformer(&quot;config.xml&quot;);
$xt->parse();
print &quot;<pre>&quot;;
print_r($xt);
print &quot;</pre>&quot;;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top