Witam, testuje różne warianty XML'a i natknąłem się na średnio zrozumiałą dla mnie rzecz.
Mam taki kod:
plik testowy.php
  1. <?php
  2. $plik_xml = 'p.xml';
  3. /**
  4.  * Klasa zamiany pliku XML na tablice w PHP
  5.  * Dodałem metode statyczną utf8_for_xml która usuwa krzaki bezpośrednio przy pobieraniu XML'a
  6.  *
  7.  * XML2Array: A class to convert XML to array in PHP
  8.  *
  9.  * Author : Abdelwahd Hannabou
  10.  *
  11.  * Usage:
  12.  * $Array = XML2Array::CreateArray('FILE_PATH');
  13.  */
  14.  
  15. class XML2Array
  16. {
  17. public static function utf8_for_xml($string)
  18. {
  19. return preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $string);
  20. }
  21.  
  22. public static function ampersandClean($string)
  23. {
  24. return preg_replace('/&/', '&amp;', $string);
  25. }
  26.  
  27. public static function CreateArray($XmlFilePath)
  28. {
  29. if (!file_exists($XmlFilePath)) {
  30. echo "Nie ma pliku";
  31. return FALSE;
  32. }
  33. $Class = array();
  34. $Class['UsersFileXml'] = self::ampersandClean(self::utf8_for_xml(file_get_contents($XmlFilePath)));
  35. /* echo "<pre>";
  36. print_r($Class['UsersFileXml']);
  37. echo "</pre>"; */
  38.  
  39. $Class['FileXml'] = simplexml_load_string($Class['UsersFileXml']);
  40. echo "<pre>";
  41. print_r($Class['FileXml']);
  42. echo "</pre>";
  43. $Class['FileJson'] = json_encode($Class['FileXml']);
  44. $Array = json_decode($Class['FileJson'],TRUE);
  45. unset($Class);
  46.  
  47. return $Array;
  48. }
  49. }
  50.  
  51. $xml = XML2Array::CreateArray($plik_xml);
  52. /* echo '<pre>';
  53. print_r($xml);
  54. echo '</pre>';
  55.  */

plik p.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <glowny>
  3. <wezel1>test</wezel1>
  4. <wezel2>test2</wezel2>
  5. <cos>napis ktory sie tu zalapal i dlatego nie widac tego co jest w "cos innego"<cosinnego>test3</cosinnego></cos>
  6. </glowny>


Nie pokazuje węzła <cosinnego> tylko widzi tam string, jak zrobić, żeby pomijał jakikolwiek string jeśli występuje na początku jakiegoś węzła a nie jest w poprawnym formacie < i > ?
Tutaj np. skrypt zachowuje się prawidłowo i pomija nie chciany string:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <glowny>
  3. <wezel1>test</wezel1>
  4. <wezel2>test2</wezel2>
  5. <cos><cosinnego>test3</cosinnego>napis ktory sie tu zalapal i widac to co jest w "cos innego"<tezwidac>to tez widac</tezwidac></cos>
  6. </glowny>