SlideShare a Scribd company logo
SimpleXML
XML XML is stand for Extensible Markup Language – a general purpose for markup language. Classified as an extensible language because it allows its users to define their own elements. XML file:- <?xml version=&quot;1.0&quot;?>  <book>      <name>Ayu</name>      <age>21</age>      <gender>Female</gender>      <address>          <current>Kuala Lumpur</current>          <permanent>Kedah</permanent>      </address>  </book> Purpose :- To facilitate the sharing of structured data across different information systems, particularly via the Internet. Encode documents and serialize data. PHP includes support two standard methods of parsing XML. SAX DOM PHP 5.0 introduces new XML extension called SimpleXML.
Processing XML Documents SAX (Simple API for XML) Involved traversing an XML document and calling specific functions as the parser encountered different types of tags. Example – one function is called to process a starting tag, another function to process an ending tag and a third function to process the data between them. DOM (Document Object Model) Involved creating a tree representation of the XML document in memory and then using the tree-traversal methods to navigate it. Once a particular node of the tree was reached, the corresponding content could be retrieved and used. Neither of these approaches was particularly user-friendly. SAX required a developer to custom-craft event handlers for each type of element encountered in an XML file. DOM approach used an object-oriented paradigm – memory-intensive and inefficient with large XML documents. PHP 4 used a number of different backend libraries for each of its different XML extensions. Leads to inconsistency in the way different XML extensions worked and thus creating interoperability concerns.
In PHP 5.0, libxml2 library is adopted as the standard library for all XML extensions and various XML extensions is obtained to operate more consistently. SimpleXML:- Developed by Sterling Hughes, Rob Richards and Marcus Borger. Made more user-friendly in parsing XML documents. An XML document is converted into an object. Turn the elements within that document into object properties which can be accessed using standard object notation. Repeated elements at the same level of the document tree are represented as an arrays. Custom element collections can be created using XPath location paths; these collections can be processed using PHP’s loop construct. PHP build must include support for SimpleXML – to use SimpleXML and PHP together. This support is enabled by default in UNIX and Windows versions of PHP 5. SimpleXML is only available for PHP 5.
Example of SimpleXML Example 1 Consider the XML file below:- <?xml version = &quot;1.0&quot; ?>  MODIFIED <pet>      <name>Polly Parrot</name>      <age>3</age>      <species>parrot</species>      <parents>          <mother>Pia Parrot</mother>          <father>Peter Parrot</father>      </parents>  </pet>   To get the content enclosed between the <name>, <age>, <species> and <parents> elements :- <?php  // set name of XML file  $file  =  &quot;pet.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // access XML data  echo  &quot;Name: &quot;  .  $xml -> name  .  &quot;\n&quot; ;  echo  &quot;Age: &quot;  .  $xml -> age  .  &quot;\n&quot; ;  echo  &quot;Species: &quot;  .  $xml -> species  .  &quot;\n&quot; ;  echo  &quot;Parents: &quot;  .  $xml -> parents -> mother  .  &quot; and &quot;  .   $xml -> parents -> father  .  &quot;\n&quot; ;  ?>
simplexml_load_file() function - accepts the path and name of the XML file to be parsed.  The result of parsing the file is a PHP object, whose properties correspond to the elements under the root element.  The character data within an element can then be accessed using standard object  ->  property notation, beginning with the root element and moving down the hierarchical path of the document.  Assign a new value to the corresponding object property. This will modify the original data. <?php  // set name of XML file  $file  =  &quot;pet.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // modify XML data  $xml -> name  =  &quot;Sammy Snail&quot; ;  $xml -> age  =  4 ;  $xml -> species  =  &quot;snail&quot; ;  $xml -> parents -> mother  =  &quot;Sue Snail&quot; ;  $xml -> parents -> father  =  &quot;Sid Snail&quot; ;  // write new data to file  file_put_contents ( $file ,  $xml -> asXML ());  ?>   Figure 11.1 : Output for Example 1
<?xml version=&quot;1.0&quot;?> <pet>   <name>Sammy Snail</name>   <age>4</age>   <species>snail</species>   <parents>   <mother>Sue Snail</mother>   <father>Sid Snail</father>   </parents> </pet> The modified XML file is shown above. The original is first read in and then the character enclosed within each element is altered by assigning new values to the corresponding object property. asXML() method is typically used to dump the XML tree back out to the standard output device. It is combined with the file_put-contents() function to overwrite the original XML document with the new data. ORIGINAL
Repeated Elements Repeated elements at the same level of the XML hierarchy are represented as an array elements and can be accessed using numeric indices. Consider the following XML file:- <?xml version = &quot;1.0&quot; ?>  <sins>      <sin>pride</sin>      <sin>envy</sin>      <sin>anger</sin>      <sin>greed</sin>      <sin>sloth</sin>      <sin>gluttony</sin>      <sin>lust</sin>  </sins>   Below is a PHP script that reads it and retrieves the data the XML file:-  <?php  // set name of XML file  $file  =  &quot;sins.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // access each <sin>  echo  $xml -> sin [ 0 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 1 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 2 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 3 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 4 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 5 ] .  &quot;\n&quot; ;  echo  $xml -> sin [ 6 ] .  &quot;\n&quot; ;  ?>
Iterate over the collection with a foreach() loop also can be used to get the same output.   <?php  // set name of XML file  $file  =  &quot;sins.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // iterate over <sin> element collection  foreach ( $xml -> sin  as  $sin ) {      echo  &quot;$sin\n&quot; ;  }  ?>   Figure 11.2 : Output for repeated elements
Element Attributes Handling  SimpleXML handles element attributes transparently. Attribute-value pairs are represented as members of a PHP associative array and can be accessed like regular array elements. Consider the codes below:- <?php // create XML string $str  = <<< XML <?xml version=&quot;1.0&quot;?> <shapes>     <shape type=&quot;circle&quot; radius=&quot;2&quot; />     <shape type=&quot;rectangle&quot; length=&quot;5&quot; width=&quot;2&quot; />     <shape type=&quot;square&quot; length=&quot;7&quot; /> </shapes> XML; // load string $xml  =  simplexml_load_string ( $str ) or die ( &quot;Unable to load XML string!&quot; ); // for each shape // calculate area foreach ( $xml -> shape  as  $shape ) {     if ( $shape [ 'type' ] ==  &quot;circle&quot; ) {          $area  =  pi () *  $shape [ 'radius' ] *  $shape [ 'radius' ];     }     elseif ( $shape [ 'type' ] ==  &quot;rectangle&quot; ) {          $area  =  $shape [ 'length' ] *  $shape [ 'width' ];     }     elseif ( $shape [ 'type' ] ==  &quot;square&quot; ) {          $area  =  $shape [ 'length' ] *  $shape [ 'length' ];     }     echo  $area . &quot;\n&quot; ; } ?>
This example creates XML dynamically and loads it into SimpleXML with the simplexml_load_string() method. The XML is then parsed with a foreach() loop and area for each shape calculated on the basis of the value of each <shape> element’s type attribute. Figure 11.3 : Element attribute handling
Custom Elements Collection SimpleXML also supports custom element collections through XPath location paths. XPath is a standard addressing mechanism for an XML document. It allows developers to access collections of elements, attributes or text nodes within a document. Consider the XML document below:- <?xml version = &quot;1.0&quot; ?>  <ingredients>      <item>          <desc>Boneless chicken breasts</desc>          <quantity>2</quantity>      </item>      <item>          <desc>Chopped onions</desc>          <quantity>2</quantity>      </item>       <item>    <desc>Ginger</desc>   <quantity>1</quantity>  </item>  <item>    <desc>Garlic</desc>    <quantity>1</quantity>  </item>  <item>     <desc>Red chili powder</desc>   <quantity>1</quantity>  </item>  <item>    <desc>Coriander seeds</desc>    <quantity>1</quantity>  </item>  <item>     <desc>Lime juice</desc>     <quantity>2</quantity>  </item>  </ingredients>
To print all the <desc> elements, iterate over the array item or create a custom collection of only the <desc> elements with the xpath() method and iterate over it. <?php  // set name of XML file  $file  =  &quot;ingredients.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // get all the <desc> elements and print  foreach ( $xml -> xpath ( '//desc' ) as  $desc ) {      echo  &quot;$desc\n&quot; ;  }  ?>   Figure 11.4 : Output using Custom Collection
Using XPath, a lot more can be done. Creating a collection of only those <desc> elements whose corresponding quantities are two or more. Consider the example given below:- <?php  // set name of XML file  $file  =  &quot;ingredients.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  // get all the <desc> elements and print  foreach ( $xml -> xpath ( '//item[quantity > 1]/desc' ) as  $desc ) {      echo  &quot;$desc\n&quot; ;  }  ?>   Figure 11.5 : Output using XPath
Codes Review Consider the codes given below, a bunch of movie reviews marked up in XML.  <?xml version = &quot;1.0&quot; ?>  <review id=&quot;57&quot; category=&quot;2&quot;>      <title>Moulin Rouge</title>      <teaser>          Baz Luhrmann's over-the-top vision of Paris at the turn of the century          is witty, sexy...and completely unforgettable      </teaser>      <cast>          <person>Nicole Kidman</person>          <person>Ewan McGregor</person>          <person>John Leguizamo</person>          <person>Jim Broadbent</person>          <person>Richard Roxburgh</person>      </cast>      <director>Baz Luhrmann</director>      <duration>120</duration>      <genre>Romance/Comedy</genre>      <year>2001</year>      <body>          A stylishly spectacular extravaganza, Moulin Rouge is hard to          categorize; it is, at different times, a love story, a costume drama,          a musical, and a comedy. Director Baz Luhrmann (well-known for the          very hip William Shakespeare's Romeo + Juliet) has taken some simple          themes - love, jealousy and obsession - and done something completely          new and different with them by setting them to music.      </body>      <rating>5</rating>  </review>
To display this review on Web site, use a PHP script to extract the data from the file and place it in the appropriate locations in an HTML template. <?php  // set name of XML file  // normally this would come through GET  // it's hard-wired here for simplicity  $file  =  &quot;57.xml&quot; ;  // load file  $xml  =  simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; );  ?>  <html>  <head><basefont face=&quot;Arial&quot;></head>  <body>  <!-- title and year -->  <h1> <?php  echo  $xml -> title ;  ?>  ( <?php  echo  $xml -> year ;  ?> )</h1>  <!-- slug -->  <h3> <?php  echo  $xml -> teaser ;  ?> </h3>  <!-- review body -->  <?php  echo  $xml -> body ;  ?>  <!-- director, cast, duration and rating -->  <p align=&quot;right&quot;/>  <font size=&quot;-2&quot;>  Director: <b> <?php  echo  $xml -> director ;  ?> </b>  <br />  Duration: <b> <?php  echo  $xml -> duration ;  ?>  min</b>  <br />  Cast: <b> <?php  foreach ( $xml -> cast -> person  as  $person ) { echo  &quot;$person &quot; ; }  ?> </b>  <br />  Rating: <b> <?php  echo  $xml -> rating ;  ?> </b>  </font>  </body>  </html>
Figure 11.6 : Output using PHP script
Summary XML is stand for Extensible Markup Language. PHP includes support two standard methods of parsing XML ; SAX and DOM. PHP 5.0 introduces new XML extension called SimpleXML. libxml2 library is adopted as the standard library for all XML extensions. Repeated elements at the same level of the XML hierarchy are represented as an array elements and can be accessed using numeric indices. Attribute-value pairs are represented as members of a PHP associative array and can be accessed like regular array elements. SimpleXML supports custom element collections through XPath location paths. XPath is a standard addressing mechanism for an XML document.
Ad

More Related Content

What's hot (20)

Awt
AwtAwt
Awt
Rakesh Patil
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
Rosie Jane Enomar
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)JavaScript Object Notation (JSON)
JavaScript Object Notation (JSON)
BOSS Webtech
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
yash jain
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Rahul Jamwal
 
Callback Function
Callback FunctionCallback Function
Callback Function
Roland San Nicolas
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 

Similar to Php Simple Xml (20)

Xmlphp
XmlphpXmlphp
Xmlphp
kiran vadariya
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
BG Java EE Course
 
Douglas Crockford Presentation Jsonsaga
Douglas Crockford Presentation JsonsagaDouglas Crockford Presentation Jsonsaga
Douglas Crockford Presentation Jsonsaga
Ajax Experience 2009
 
The JSON Saga
The JSON SagaThe JSON Saga
The JSON Saga
kaven yan
 
XML and Web Services with PHP5 and PEAR
XML and Web Services with PHP5 and PEARXML and Web Services with PHP5 and PEAR
XML and Web Services with PHP5 and PEAR
Stephan Schmidt
 
Jsonsaga
JsonsagaJsonsaga
Jsonsaga
nohmad
 
2310 b 12
2310 b 122310 b 12
2310 b 12
Krazy Koder
 
XML processing with perl
XML processing with perlXML processing with perl
XML processing with perl
Joe Jiang
 
Sax Dom Tutorial
Sax Dom TutorialSax Dom Tutorial
Sax Dom Tutorial
vikram singh
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
Jussi Pohjolainen
 
The Document Object Model
The Document Object ModelThe Document Object Model
The Document Object Model
Khou Suylong
 
XML
XMLXML
XML
Vahideh Zarea Gavgani
 
XML and XSLT
XML and XSLTXML and XSLT
XML and XSLT
Andrew Savory
 
XML Transformations With PHP
XML Transformations With PHPXML Transformations With PHP
XML Transformations With PHP
Stephan Schmidt
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
srinivasanjayakumar
 
Introduction To Xml
Introduction To XmlIntroduction To Xml
Introduction To Xml
bdebruin
 
Xml
XmlXml
Xml
Kunal Gaind
 
Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4Inroduction to XSLT with PHP4
Inroduction to XSLT with PHP4
Stephan Schmidt
 
XML and PHP 5
XML and PHP 5XML and PHP 5
XML and PHP 5
Adam Trachtenberg
 
XML
XMLXML
XML
Mukesh Tekwani
 
Ad

More from mussawir20 (20)

Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Rss
Php RssPhp Rss
Php Rss
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php Oop
Php OopPhp Oop
Php Oop
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Html
HtmlHtml
Html
mussawir20
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Object Range
Object RangeObject Range
Object Range
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 
Ad

Recently uploaded (20)

Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 

Php Simple Xml

  • 2. XML XML is stand for Extensible Markup Language – a general purpose for markup language. Classified as an extensible language because it allows its users to define their own elements. XML file:- <?xml version=&quot;1.0&quot;?> <book>     <name>Ayu</name>     <age>21</age>     <gender>Female</gender>     <address>         <current>Kuala Lumpur</current>         <permanent>Kedah</permanent>     </address> </book> Purpose :- To facilitate the sharing of structured data across different information systems, particularly via the Internet. Encode documents and serialize data. PHP includes support two standard methods of parsing XML. SAX DOM PHP 5.0 introduces new XML extension called SimpleXML.
  • 3. Processing XML Documents SAX (Simple API for XML) Involved traversing an XML document and calling specific functions as the parser encountered different types of tags. Example – one function is called to process a starting tag, another function to process an ending tag and a third function to process the data between them. DOM (Document Object Model) Involved creating a tree representation of the XML document in memory and then using the tree-traversal methods to navigate it. Once a particular node of the tree was reached, the corresponding content could be retrieved and used. Neither of these approaches was particularly user-friendly. SAX required a developer to custom-craft event handlers for each type of element encountered in an XML file. DOM approach used an object-oriented paradigm – memory-intensive and inefficient with large XML documents. PHP 4 used a number of different backend libraries for each of its different XML extensions. Leads to inconsistency in the way different XML extensions worked and thus creating interoperability concerns.
  • 4. In PHP 5.0, libxml2 library is adopted as the standard library for all XML extensions and various XML extensions is obtained to operate more consistently. SimpleXML:- Developed by Sterling Hughes, Rob Richards and Marcus Borger. Made more user-friendly in parsing XML documents. An XML document is converted into an object. Turn the elements within that document into object properties which can be accessed using standard object notation. Repeated elements at the same level of the document tree are represented as an arrays. Custom element collections can be created using XPath location paths; these collections can be processed using PHP’s loop construct. PHP build must include support for SimpleXML – to use SimpleXML and PHP together. This support is enabled by default in UNIX and Windows versions of PHP 5. SimpleXML is only available for PHP 5.
  • 5. Example of SimpleXML Example 1 Consider the XML file below:- <?xml version = &quot;1.0&quot; ?> MODIFIED <pet>     <name>Polly Parrot</name>     <age>3</age>     <species>parrot</species>     <parents>         <mother>Pia Parrot</mother>         <father>Peter Parrot</father>     </parents> </pet> To get the content enclosed between the <name>, <age>, <species> and <parents> elements :- <?php // set name of XML file $file = &quot;pet.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // access XML data echo &quot;Name: &quot; . $xml -> name . &quot;\n&quot; ; echo &quot;Age: &quot; . $xml -> age . &quot;\n&quot; ; echo &quot;Species: &quot; . $xml -> species . &quot;\n&quot; ; echo &quot;Parents: &quot; . $xml -> parents -> mother . &quot; and &quot; .   $xml -> parents -> father . &quot;\n&quot; ; ?>
  • 6. simplexml_load_file() function - accepts the path and name of the XML file to be parsed. The result of parsing the file is a PHP object, whose properties correspond to the elements under the root element. The character data within an element can then be accessed using standard object -> property notation, beginning with the root element and moving down the hierarchical path of the document. Assign a new value to the corresponding object property. This will modify the original data. <?php // set name of XML file $file = &quot;pet.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // modify XML data $xml -> name = &quot;Sammy Snail&quot; ; $xml -> age = 4 ; $xml -> species = &quot;snail&quot; ; $xml -> parents -> mother = &quot;Sue Snail&quot; ; $xml -> parents -> father = &quot;Sid Snail&quot; ; // write new data to file file_put_contents ( $file , $xml -> asXML ()); ?> Figure 11.1 : Output for Example 1
  • 7. <?xml version=&quot;1.0&quot;?> <pet> <name>Sammy Snail</name> <age>4</age> <species>snail</species> <parents> <mother>Sue Snail</mother> <father>Sid Snail</father> </parents> </pet> The modified XML file is shown above. The original is first read in and then the character enclosed within each element is altered by assigning new values to the corresponding object property. asXML() method is typically used to dump the XML tree back out to the standard output device. It is combined with the file_put-contents() function to overwrite the original XML document with the new data. ORIGINAL
  • 8. Repeated Elements Repeated elements at the same level of the XML hierarchy are represented as an array elements and can be accessed using numeric indices. Consider the following XML file:- <?xml version = &quot;1.0&quot; ?> <sins>     <sin>pride</sin>     <sin>envy</sin>     <sin>anger</sin>     <sin>greed</sin>     <sin>sloth</sin>     <sin>gluttony</sin>     <sin>lust</sin> </sins> Below is a PHP script that reads it and retrieves the data the XML file:- <?php // set name of XML file $file = &quot;sins.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // access each <sin> echo $xml -> sin [ 0 ] . &quot;\n&quot; ; echo $xml -> sin [ 1 ] . &quot;\n&quot; ; echo $xml -> sin [ 2 ] . &quot;\n&quot; ; echo $xml -> sin [ 3 ] . &quot;\n&quot; ; echo $xml -> sin [ 4 ] . &quot;\n&quot; ; echo $xml -> sin [ 5 ] . &quot;\n&quot; ; echo $xml -> sin [ 6 ] . &quot;\n&quot; ; ?>
  • 9. Iterate over the collection with a foreach() loop also can be used to get the same output. <?php // set name of XML file $file = &quot;sins.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // iterate over <sin> element collection foreach ( $xml -> sin as $sin ) {     echo &quot;$sin\n&quot; ; } ?> Figure 11.2 : Output for repeated elements
  • 10. Element Attributes Handling SimpleXML handles element attributes transparently. Attribute-value pairs are represented as members of a PHP associative array and can be accessed like regular array elements. Consider the codes below:- <?php // create XML string $str = <<< XML <?xml version=&quot;1.0&quot;?> <shapes>     <shape type=&quot;circle&quot; radius=&quot;2&quot; />     <shape type=&quot;rectangle&quot; length=&quot;5&quot; width=&quot;2&quot; />     <shape type=&quot;square&quot; length=&quot;7&quot; /> </shapes> XML; // load string $xml = simplexml_load_string ( $str ) or die ( &quot;Unable to load XML string!&quot; ); // for each shape // calculate area foreach ( $xml -> shape as $shape ) {     if ( $shape [ 'type' ] == &quot;circle&quot; ) {          $area = pi () * $shape [ 'radius' ] * $shape [ 'radius' ];     }     elseif ( $shape [ 'type' ] == &quot;rectangle&quot; ) {          $area = $shape [ 'length' ] * $shape [ 'width' ];     }     elseif ( $shape [ 'type' ] == &quot;square&quot; ) {          $area = $shape [ 'length' ] * $shape [ 'length' ];     }     echo $area . &quot;\n&quot; ; } ?>
  • 11. This example creates XML dynamically and loads it into SimpleXML with the simplexml_load_string() method. The XML is then parsed with a foreach() loop and area for each shape calculated on the basis of the value of each <shape> element’s type attribute. Figure 11.3 : Element attribute handling
  • 12. Custom Elements Collection SimpleXML also supports custom element collections through XPath location paths. XPath is a standard addressing mechanism for an XML document. It allows developers to access collections of elements, attributes or text nodes within a document. Consider the XML document below:- <?xml version = &quot;1.0&quot; ?> <ingredients>     <item>         <desc>Boneless chicken breasts</desc>         <quantity>2</quantity>     </item>     <item>         <desc>Chopped onions</desc>         <quantity>2</quantity>     </item>      <item> <desc>Ginger</desc> <quantity>1</quantity> </item> <item>  <desc>Garlic</desc>   <quantity>1</quantity> </item> <item>    <desc>Red chili powder</desc>  <quantity>1</quantity> </item> <item>   <desc>Coriander seeds</desc>   <quantity>1</quantity> </item> <item>    <desc>Lime juice</desc>    <quantity>2</quantity> </item> </ingredients>
  • 13. To print all the <desc> elements, iterate over the array item or create a custom collection of only the <desc> elements with the xpath() method and iterate over it. <?php // set name of XML file $file = &quot;ingredients.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // get all the <desc> elements and print foreach ( $xml -> xpath ( '//desc' ) as $desc ) {     echo &quot;$desc\n&quot; ; } ?> Figure 11.4 : Output using Custom Collection
  • 14. Using XPath, a lot more can be done. Creating a collection of only those <desc> elements whose corresponding quantities are two or more. Consider the example given below:- <?php // set name of XML file $file = &quot;ingredients.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); // get all the <desc> elements and print foreach ( $xml -> xpath ( '//item[quantity > 1]/desc' ) as $desc ) {     echo &quot;$desc\n&quot; ; } ?> Figure 11.5 : Output using XPath
  • 15. Codes Review Consider the codes given below, a bunch of movie reviews marked up in XML. <?xml version = &quot;1.0&quot; ?> <review id=&quot;57&quot; category=&quot;2&quot;>     <title>Moulin Rouge</title>     <teaser>         Baz Luhrmann's over-the-top vision of Paris at the turn of the century         is witty, sexy...and completely unforgettable     </teaser>     <cast>         <person>Nicole Kidman</person>         <person>Ewan McGregor</person>         <person>John Leguizamo</person>         <person>Jim Broadbent</person>         <person>Richard Roxburgh</person>     </cast>     <director>Baz Luhrmann</director>     <duration>120</duration>     <genre>Romance/Comedy</genre>     <year>2001</year>     <body>         A stylishly spectacular extravaganza, Moulin Rouge is hard to         categorize; it is, at different times, a love story, a costume drama,         a musical, and a comedy. Director Baz Luhrmann (well-known for the         very hip William Shakespeare's Romeo + Juliet) has taken some simple         themes - love, jealousy and obsession - and done something completely         new and different with them by setting them to music.     </body>     <rating>5</rating> </review>
  • 16. To display this review on Web site, use a PHP script to extract the data from the file and place it in the appropriate locations in an HTML template. <?php // set name of XML file // normally this would come through GET // it's hard-wired here for simplicity $file = &quot;57.xml&quot; ; // load file $xml = simplexml_load_file ( $file ) or die ( &quot;Unable to load XML file!&quot; ); ?> <html> <head><basefont face=&quot;Arial&quot;></head> <body> <!-- title and year --> <h1> <?php echo $xml -> title ; ?> ( <?php echo $xml -> year ; ?> )</h1> <!-- slug --> <h3> <?php echo $xml -> teaser ; ?> </h3> <!-- review body --> <?php echo $xml -> body ; ?> <!-- director, cast, duration and rating --> <p align=&quot;right&quot;/> <font size=&quot;-2&quot;> Director: <b> <?php echo $xml -> director ; ?> </b> <br /> Duration: <b> <?php echo $xml -> duration ; ?> min</b> <br /> Cast: <b> <?php foreach ( $xml -> cast -> person as $person ) { echo &quot;$person &quot; ; } ?> </b> <br /> Rating: <b> <?php echo $xml -> rating ; ?> </b> </font> </body> </html>
  • 17. Figure 11.6 : Output using PHP script
  • 18. Summary XML is stand for Extensible Markup Language. PHP includes support two standard methods of parsing XML ; SAX and DOM. PHP 5.0 introduces new XML extension called SimpleXML. libxml2 library is adopted as the standard library for all XML extensions. Repeated elements at the same level of the XML hierarchy are represented as an array elements and can be accessed using numeric indices. Attribute-value pairs are represented as members of a PHP associative array and can be accessed like regular array elements. SimpleXML supports custom element collections through XPath location paths. XPath is a standard addressing mechanism for an XML document.