aRo` automating your e-commerce

10Aug/07
This blog has been neglected due to the success of Solidshops.com

writing the recursive path for all items that contain data in XML file

This little php functions shows how to write the recursive XMLpath for all nodes that contain values.

XML:
  1. $xmlstr = <<<XML
  2. <?xml version='1.0' standalone='yes'?>
  3. <movies>
  4.  <movie>
  5.   <title>PHP: Behind the Parser</title>
  6.   <characters>
  7.    <character>
  8.     <name>Ms. Coder</name>
  9.     <actor>Onlivia Actora</actor>
  10.    </character>
  11.    <character>
  12.     <name>Mr. Coder</name>
  13.     <actor>El Act&#211;r</actor>
  14.    </character>
  15.   </characters>
  16.   <plot>
  17.    So, this language. It's like, a programming language. Or is it a
  18.    scripting language? All is revealed in this thrilling horror spoof
  19.    of a documentary.
  20.   </plot>
  21.   <rating type="thumbs">7</rating>
  22.   <rating type="stars">5</rating>
  23.  </movie>
  24. </movies>
  25. XML;

PHP:
  1. $xml = new SimpleXMLElement($xmlstr);
  2. //SimpleXML_recursive($xml-&gt;xpath('//movie/characters/character'));
  3. SimpleXML_recursive($xml);function SimpleXML_recursive($xml,$parent="")
  4. {
  5. $child_count = 0;
  6. foreach($xml as $key=&gt;$value)
  7. {
  8. $child_count++;
  9. if(SimpleXML_recursive($value,$parent."/".$key) == 0)  // no childern
  10. {
  11. if($value-&gt;attributes() &lt;&gt; ""){
  12. $att = "[@".$value-&gt;attributes()."]";
  13. }
  14. print($parent . "/" . (string)$key .$att. "
  15. \n");
  16. }
  17. }
  18. return $child_count;
  19. }

This is the result:

/movie/title
/movie/characters/character/name
/movie/characters/character/actor
/movie/characters/character/name
/movie/characters/character/actor
/movie/plot
/movie/rating[@thumbs]
/movie/rating[@stars]

Now you can use this code to map the XML fields against the database fields.

Popularity: 2% [?]

Filed under: php, xml Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.