Tag Archives: XML Parser

Modify XML node element value php

XML File – test.xml
===============
<?xml version=”1.0″ encoding=”UTF-8″?>
<PHPCodez>
<Update>
<Time>26</Time>
</Update>
</PHPCodez>

 

PHPCode

========

<?php
$xmlFIle    =       “test.xml”;
$xmlString       =  file_get_contents($xmlFIle);
$content=simplexml_load_string($xmlString);
echo $content->Update->Time;
$content->Update->Time = date(“Y-M-d h:i:s”);
$content->asXML($xmlFIle);
?>

xml_set_unparsed_entity_decl_handler()

It  set up unparsed entity declaration handler

Example

<?php
$xmlparser=xml_parser_create();
function char($xmlparser,$data) {
echo $data;
}

function unparsed_ent_handler_func($xmlparser,$entname,$base,$sysID,$pubID,$notname){
echo $entname.$sysID.$pubID.$notname.
}

xml_set_character_data_handler($xmlparser,”char”);
xml_set_unparsed_entity_decl_handler($xmlparser,”unparsed_ent_handler_func”);

$fp=fopen(“test.xml”,”r”);

while ($data=fread($fp,4096)) {
xml_parse($xmlparser,$data,feof($fp)) or die(“Failed”);
}

xml_parser_free($xmlparser);
?>

xml_set_processing_instruction_handler()

It  set up processing instruction (PI) handler

Example

<?php
$xmlparser=xml_parser_create();

function char($xmlparser,$data) {
echo $data;
}

function pi_handler_func($xmlparser, $target, $data) {
echo $target.$data;
}

xml_set_character_data_handler($xmlparser,”char”);
xml_set_processing_instruction_handler($xmlparser, “pi_handler_func”);
$fp=fopen(“book.xml”,”r”);

while ($data=fread($fp,4096)){
xml_parse($xmlparser,$data,feof($fp));
}

xml_parser_free($xmlparser);
?>

xml_set_object()

It uses XML Parser within an object

Example

<?php
class XMLParser{
var $xmlparser;
function XMLParser(){
$this->xmlparser = xml_parser_create();
xml_set_object($this->xmlparser, $this);
xml_set_character_data_handler($this->xmlparser,”char”);
xml_set_element_handler($this->xmlparser, “start_tag”,”end_tag”);
}

function parse($data){
xml_parse($this->xmlparser, $data);
}

function parse_File($xmlfile){
$fp = fopen($xmlfile, ‘r’);
while ($xmldata = fread($fp, 4096)){
if(!xml_parse($this->xmlparser, $xmldata)){
die(“Failed”);
}
}
}

function start_tag($xmlparser, $tag, $attributes){
print $tag . “n”;
}

function end_tag(){}

function char($xmlparser,$data){
echo $data . “n”;
}

function close_Parser(){
xml_parser_free($this->xmlparser);
}
}

$myxmlparser = new XMLParser();
$myxmlparser->parse_File(“book.xml”);
$myxmlparser->close_parser();
?>