php & xml: SimpleXMLElement and xpath using example

Trabla: php & xml: SimpleXMLElement and xpath using example

Solving:

1. XML file  "test.xml"

<?xml version="1.0" encoding="UTF-8"?>

<Sentences version="3">

<Author id="1">Jenny</Author >

<Author id="2">Helen</Author >

 
<Sentence id="1">

<Word id="1" >Hello</Word >
<Word id="2" >World</Word >

</Sentence >
 
<Sentence id="2">

<Word id="3" >The</Word >
<Word id="4" >Sun</Word >
<Word id="5" >is</Word >
<Word id="6" >shining</Word >

</Sentence >

</Sentences>

2.  Php code

//Load xml file content
$xml = file_get_contents( "http://mysite.com/xml/test.xml");

$sentences = new SimpleXMLElement( $xml );  

//Print version attribute from tag Sentences
echo (string)$sentences [0]['version'];  // 3  -> <Sentences version="3">

//Iteration through Author tags

foreach ( $sentences ->xpath('Author') as $author ) {

  echo (string)$author ;  // Author tag element value e.g. Jenny, Helen
  echo (string)$author ['id']; // "id" attribute of Author tag

}

//Iteration through Word tags (in both Sentence )

foreach ( $sentences ->xpath('Sentence/Word') as $word ) {

  echo (string)$word ;  // Word tag value e.g. Hello, World, The, Sun, is, shining
          echo (string)$word ['id']; // "id" attribute of Word tag

}


No comments:

Post a Comment