Learn How to parse xml using php

XML is the acronym for Extensible Markup Language. XML is used to structure, store and transport data from one system to another. It uses opening and closing tags.
There are two major types of XML parsers in php
1. Tree-Based Parsers - Example of tree-based parsers are SimpleXML and DOM
2. Event-Based Parsers - Example of event-based parsers are XMLReader and XML Expat Parser

Create XML parse as per below code.
<?php
$file = "xml_beginner.xml";

function contents($parser, $data){
echo $data;
}

function startTag($parser, $data){
echo "";
}

function endTag($parser, $data){
echo "

";
}

$xml_parser = xml_parser_create();

xml_set_element_handler($xml_parser, "startTag", "endTag");

xml_set_character_data_handler($xml_parser, "contents");

$fp = fopen($file, "r");

$data = fread($fp, 80000);

if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}

$xmldata = new SimpleXMLElement($data);
print_r($xmldata);

xml_parser_free($xml_parser);

fclose($fp);
?>

The PHP simplexml_load_string() function is used to read XML data from a string.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

61072