Page 1 of 1

parsing xml file [solved]

Posted: Sat Oct 21, 2006 2:39 am
by itsmani1
I am trying to parse xml using php 4.x.x file is getting opened and loaded into $data var scuccessfully. but don' tknow why rest of the code is not working

Code: Select all

<?PHP
	$fp = fopen("tst1.xml",r);
	$data = fread($fp,1024);

	$parser = xml_parser_create();
	
	xml_set_element_handler($parser, "startElement", "endElement");
	xml_set_character_data_handler($parser, "characterData");
	xml_set_default_handler($parser, "defaultHandler");

	function characterData($xml_parser, $data1) 
	{
		echo "Start";
	}
	function startElement($xml_parser, $name, $attrs)
	{
		echo "End";
	}
	function endElement($xml_parser, $name)
	{
		echo "Data";
	}
	function defaultHandler($xml_parser, $data1) 
	{
		echo "Default";
	}
	xml_parser_free($parser);
?>

Posted: Sat Oct 21, 2006 5:19 am
by akimm
Possible because you didn't fclose?

Posted: Sat Oct 21, 2006 7:36 am
by impulse()
If you ever plan to put that data neatly into a MySQL DB then please let me see the code for it. 2 weeks solid and I havn't managed to do it yet.

:cry:

Posted: Sat Oct 21, 2006 1:52 pm
by volka
I don't see a call of xml_parse().

Posted: Fri Oct 27, 2006 12:20 am
by itsmani1
where i should call this xml_parse() thing?

Posted: Fri Oct 27, 2006 3:10 am
by volka
Compare your script with the examples at http://www.php.net/manual/en/ref.xml.php

Posted: Fri Oct 27, 2006 4:47 am
by itsmani1
here is the working code:

Code: Select all

$file = "tst1.xml";
function startElement($parser, $name, $attrs)
{
}
function endElement($parser, $name)
{
}
function characterData($parser, $name)
{
   echo $name."<BR />";
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen($file, "r");
$data = fread($fp, 4096);
xml_parse($xml_parser, $data);
xml_parser_free($xml_parser);
output is like: you can see every 2nd <BR /> is empty. in xml file its like "<size width="300" height="300" />" i wanted to show its values as well 2nd if i want to fetch only vlaues of size what i need to do?

Code: Select all

<BR />
		<BR />AmericanPie.jpg<BR />
		<BR />
		<BR />Abdul Mannan<BR />
	<BR />
	<BR />
		<BR />Cantaloupe.jpg<BR />
		<BR />
		<BR />Cantaloupe<BR />
	<BR />
	<BR />
		<BR />CitrusSlices.jpg<BR />
		<BR />
		<BR />Citrus For Summer<BR />
	<BR />
	<BR />
		<BR />CitrusSlices.jpg<BR />
		<BR />
		<BR />Citrus For Summer<BR />
	<BR />
<BR />

Posted: Fri Oct 27, 2006 4:54 am
by volka
Do you have to use the sax xml extension?
simplexml or dom might be more to your liking.

Posted: Fri Oct 27, 2006 6:34 am
by itsmani1

Code: Select all

function sxml_to_array($xml)
{
	$arr = array();
	$x = 0;
	foreach($xml as $a=>$b)
	{

		$arr[$a][$x] =  array();
		// Looking for ATTRIBUTES
		$att = $b->attributes();
		foreach($att as $c=>$d)
		{
			$arr[$a][$x]['@'][$c] = (string) $d;
		}

		// Getting CDATA
		$arr[$a][$x]['cdata'] = trim((string) utf8_decode($b));
		
		// Processing CHILD NODES
		$arr[$a][$x]['nodes'] = sxml_to_array($b);
		$x++;
	}
	return $arr;
}

$xml = simplexml_load_file('tst1.xml');
$arr = sxml_to_array($xml);
print("<pre>");
print_r($arr);
print("</pre>");
Now problem is i don't know how to parse arrays.
Output is like :

Code: Select all

Array
(
    [image] => Array
        (
            [0] => Array
                (
                    [cdata] => 
                    [nodes] => Array
                        (
                            [filename] => Array
                                (
                                    [0] => Array
                                        (
                                            [cdata] => AmericanPie.jpg
                                            [nodes] => Array
                                                (
                                                )

                                        )

                                )

                            [size] => Array
                                (
                                    [1] => Array
                                        (
                                            [@] => Array
                                                (
                                                    [width] => 300
                                                    [height] => 300
                                                )

                                            [cdata] => 
                                            [nodes] => Array
                                                (
                                                )

                                        )

                                )

                            [name] => Array
                                (
                                    [2] => Array
                                        (
                                            [cdata] => Abdul Mannan
                                            [nodes] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

Posted: Fri Oct 27, 2006 12:19 pm
by volka
please provide a sample xml file.

Posted: Fri Oct 27, 2006 5:00 pm
by kingconnections
Maybe this will help, code is not commented very well but you will get the point.

Code: Select all

<?php
 if($_SERVER['argc'] != 2){  
        die('computer_status.php Expects Only one argument: Usage: computer_status.php <filename.xml>'); 
    } 

$filename = $argv[1];
set_time_limit(0);
$myServerECM = "localhost"; 
$myUserECM = "user"; 
$myPassECM = "password"; 
$myDB2= "Wsus";


  $dbConn = mssql_connect($myServerECM, $myUserECM, $myPassECM);
  if (!$dbConn){
   print "<h3>problem connecting to database...</h3>\n";
  } // end if
  
  $select = @mssql_select_db("$myDB2");
  if (!$select){
    echo "problem selecting to database" . "<br>\n";
}


$query ="TRUNCATE TABLE ComputerStatus";
$result = mssql_query($query, $dbConn);
//$query = "INSERT INTO nettools_up2date Values ('$val','1','0','0','0')";
  
//$result = mssql_query($query, $dbConn);

if (file_exists($filename)) {
   $xml = simplexml_load_file($filename);
 
  // var_dump($xml);
} else {
   exit("Failed to open $filename.");
}

$rowcount=0;
foreach($xml->Computer as $computer)
{
	//echo"-- $computer[Name]  ";
	//echo"$computer[LastReportedStatus]<br>";
	
	
foreach ($computer->UpdateStatus->Update as $update)
{
	//echo"<br>$update[Title] --- $update[Status]";
	
	$name = "$computer[Name]";	
	$query = "INSERT INTO ComputerStatus Values ('$name','$computer[LastReportedStatus]','$update[Title]','$update[Status]')";
	//echo "$query";
	$result = mssql_query($query, $dbConn);
	$rowcount++;
	
	}
}

echo "$rowcount rows have been imported";
?>
And the XML for the Example:

Code: Select all

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ComputerStatus>
    <Computer Name="server1" LastReportedStatus="7/17/2006 7:49:23 PM">
        <UpdateStatus>
            <Update Title="Security Update for Windows Media Player 10 for Windows XP (KB917734)" Status="NotApplicable" />
            <Update Title="Security Update, February 14, 2002 (Internet Explorer 5.5)" Status="NotApplicable" />
            <Update Title="Security Update for Windows Server 2003 x64 Edition (KB896358)" Status="NotApplicable" />
            <Update Title="Visio 2003 Service Pack 2" Status="NotApplicable" />
            <Update Title="Security Update, February 14, 2002 (Internet Explorer 5.01)" Status="NotApplicable" />
            <Update Title="Security Update for Windows Server 2003 x64 Edition (KB904706)" Status="NotApplicable" />
            <Update Title="Security Update for Windows XP (KB914389)" Status="NotApplicable" />
            <Update Title="Security Update for Windows XP (KB824151)" Status="NotApplicable" />
            <Update Title="Windows Server 2003 Service Pack 1" Status="Installed" />
            <Update Title="Update Rollup 1 for Windows 2000 Service Pack 4 (KB891861)" Status="NotApplicable" />
            <Update Title="Security Update for Windows 2000 (KB917953)" Status="NotApplicable" />
            <Update Title="Update for Windows Server 2003 (KB910437)" Status="Installed" />
        </UpdateStatus>
    </Computer>
</ComputerStatus>

Posted: Sat Oct 28, 2006 12:11 am
by itsmani1
here is sample xml

Code: Select all

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
	<GetVenueListResponse xmlns="http://www.eventinventory.com/webservices/">
		<GetVenueListResult>
		<ROOT xmlns="">
			<METHODINFO>
				<channelName>Basic View</channelName>
				<methodName>GetVenueList</methodName>
				<parameters>APPCLIENT_ID=2220&EVENT_ID=6&STARTDATE=&INCDAYS=</parameters>
				<processTime type="milliseconds">105.8207</processTime>
			</METHODINFO>
			<DATA xmlns:sql="urn:schemas-microsoft-com:xml-sql">
				<row THISID="1987" THISNAME="Alliance Theatre" ST="GA" />
				<row THISID="238" THISNAME="Broward Center Amaturo" ST="FL" />
				<row THISID="536" THISNAME="Fabulous Fox Theatre - St. Louis" ST="MO" />
				<row THISID="2233" THISNAME="Ford's Theatre" ST="DC" />
				<row THISID="657" THISNAME="Goodman Theatre - Albert" ST="IL" />
				<row THISID="945" THISNAME="Lowell Memorial Auditorium" ST="MA" />
				<row THISID="1598" THISNAME="Stage Theatre" ST="CO" />
				<row THISID="2963" THISNAME="Walnut Street Theatre" ST="PA" />
			</DATA>
		</ROOT>
		</GetVenueListResult>
	</GetVenueListResponse>
</soap:Body>
</soap:Envelope>

Posted: Sat Oct 28, 2006 3:21 am
by itsmani1
using this code i been able to successfully parse the xml.

Code: Select all

$file = "tst1.xml";
function trustedFile($file)
{
	// only trust local files owned by ourselves
	if (!eregi("^([a-z]+)://", $file) && fileowner($file) == getmyuid())
	{
		return true;
	}
	return false;
}
function startElement($parser, $name, $attribs)
{
	echo "<";
	echo "<font color=\"#0000cc\">$name</font>";
	if (count($attribs))
	{
		foreach ($attribs as $k => $v)
		{
			echo " <font color=\"#009900\">$k</font>=\"<font color=\"#990000\">$v</font>\"";
		}
	}
	echo ">";
}
function endElement($parser, $name)
{
	echo "</<font color=\"#0000cc\">$name</font>>";
}
function characterData($parser, $data)
{
	echo "<b>$data</b>";
}

function new_xml_parser($file)
{
	global $parser_file;
	$xml_parser = xml_parser_create();
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");

	if (!($fp = @fopen($file, "r")))
	{
		return false;
	}
	if (!is_array($parser_file))
	{
		settype($parser_file, "array");
	}
	$parser_file[$xml_parser] = $file;
	return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
   die("could not open XML input");
}
echo "<pre>";
while ($data = fread($fp, 4096))
{
	if (!xml_parse($xml_parser, $data, feof($fp)))
	{
		die(sprintf("XML error: %s at line %d\n",xml_error_string(xml_get_error_code($xml_parser)),                  xml_get_current_line_number($xml_parser)));
	}
}
echo "</pre>";
echo "parse complete\n";
xml_parser_free($xml_parser);