Saturday, 5 May 2018

Read XML file data with regular expression using PHP.

Reading XML file with regular expression is useful when there is some minor mistake in your XML file.( like code which write the data on XML in my previous post).

<?php $xml = "";
 $f = fopen( 'data.xml', 'r' );
 while( $data = fread( $f, 4096 ) ) { $xml .= $data; } fclose( $f );
 preg_match_all( "/\<book\>(.*?)\<\/book\>/s", $xml, $bookblocks );
?>
 <table>
 <?php 
foreach( $bookblocks[1] as $block ) { 
?>
 <tr><td>
 <?php
 preg_match_all( "/\<textbox\>(.*?)\<\/textbox\>/", $block, $author );
 preg_match_all( "/\<name\>(.*?)\<\/name\>/", $block, $title );
 preg_match_all( "/\<file\>(.*?)\<\/file\>/", $block, $publisher );
 echo( $title[1][0]." - ".$author[1][0]." - ". $publisher[1][0]."\n" ); 
echo "\n";
 ?> 
</td></tr>
</table>
 <?php
 } 
?>

Above code read the file in one string. And using regex function this code reads all book element.
Drawback of regular expression is it does not check the XML is well formed or not. Such kind of code can not be accepted when XML directly come from user.


No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...