Tuesday, January 22, 2008

XML Parsar

1. First Example


//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --
";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}

//Function to use at the end of an element
function stop($parser,$element_name)
{
echo "
";
}

//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}

//Specify element handler
xml_set_element_handler($parser,"start","stop");

//Specify data handler
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen("test.xml","r");

//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

//Free the XML parser
xml_parser_free($parser);

?>



2. Second Example with dom

Xml file



Jack Herrington
PHP Hacks
O'Reilly


Jack Herrington
Podcasting Hacks
O'Reilly





****************Reading books **********

$doc = new DOMDocument();
$doc->load( 'books.xml' );

$books = $doc->getElementsByTagName( "book" );
foreach( $books as $book )
{
$authors = $book->getElementsByTagName( "author" );
$author = $authors->item(0)->nodeValue;

$publishers = $book->getElementsByTagName( "publisher" );
$publisher = $publishers->item(0)->nodeValue;

$titles = $book->getElementsByTagName( "title" );
$title = $titles->item(0)->nodeValue;

echo "$title - $author - $publisher\n";
}
?>



Writing XML Files

$books = array();
$books [] = array(
'title' => 'PHP Hacks',
'author' => 'Jack Herrington',
'publisher' => "O'Reilly"
);
$books [] = array(
'title' => 'Podcasting Hacks',
'author' => 'Jack Herrington',
'publisher' => "O'Reilly"
);
?>


foreach( $books as $book )
{
?>

<?php echo( $book['title'] ); ?>





}
?>






3.Simple XML for Php 5.0

//load xml
$books = simplexml_load_file('examples/books.xml');
//loop through the books
foreach ($books->book as $book) {

printf("Title: %s\n", $book->title);
printf("Year: %s\n", $book->year);
print "----\n";
}
?>

No comments: