Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Mini parser XML, Klasa, PHP 4 i 5
kicaj
post
Post #1





Grupa: Zarejestrowani
Postów: 1 640
Pomógł: 28
Dołączył: 13.02.2003
Skąd: Międzyrzecz/Poznań

Ostrzeżenie: (0%)
-----


  1. <?php
  2.  
  3. class XML
  4. {
  5. // Dla PHP5
  6. function __construct( $strFileName )
  7. {
  8. if( file_exists( $strFileName ) )
  9. {
  10. $this -> resFileContent = file_get_contents( $strFileName );
  11. }
  12. else
  13. {
  14. // W razie niepowodzenia, zaladowanie pliku z opisem problemu
  15. $this -> resFileContent = file_get_contents( 'resource/error.xml' );
  16. }
  17. }
  18.  
  19. // Dla PHP4
  20. function XML( $strFileName )
  21. {
  22. $this -> __construct( $strFileName );
  23. }
  24.  
  25. function getContent( $strTagName )
  26. {
  27. preg_match_all( '|<'. $strTagName .'(.*)>(.*)</'. $strTagName .'>|isU', $this -> resFileContent, $arrContentTags );
  28.  
  29. for( $intIterTags = 0; $intIterTags < count( $arrContentTags[0] ); $intIterTags++ )
  30. {
  31. return $arrContentTags[2][$intIterTags];
  32. }
  33. }
  34.  
  35. function getAttributes( $strTagName, $strAttributeName )
  36. {
  37. preg_match_all( '|<'. $strTagName .'(.*)>(.*)</'. $strTagName .'>|isU', $this -> resFileContent, $arrContentTags );
  38.  
  39. for( $intIterTags = 0; $intIterTags < count( $arrContentTags[1] ); $intIterTags++ )
  40. {
  41. if( !empty( $arrContentTags[1][$intIterTags] ) )
  42. {
  43. $arrContentAttributes = explode( ' ', $arrContentTags[1][$intIterTags] );
  44.  
  45. array_shift( $arrContentAttributes );
  46.  
  47. for( $intIterAttributes = 0; $intIterAttributes < count( $arrContentAttributes ); $intIterAttributes++ )
  48. {
  49. $arrContentAttributesElements = explode( '=', $arrContentAttributes[$intIterAttributes] );
  50.  
  51. if( $arrContentAttributesElements[0] == $strAttributeName )
  52. {
  53. // Zabezpiecznie przed roznymi sposobami okreslenia wartosci atrybutow
  54. $arrDeleteQuotes[] = ''';
  55. $arrDeleteQuotes[] = '&#092;"';
  56.  
  57. return str_replace( $arrDeleteQuotes, '', $arrContentAttributesElements[1] );
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }
  64. ?>

XML:
  1. <? xml version="1.1" encoding="ISO-8859-2" ?>
  2.  
  3. <index>
  4.    <page>Strona główna</page>
  5.    <author>kicaj_</author>
  6.    <mail antispam="yes">kicaj@m-cz.net</mail>
  7.    <content htmlcode="yes">
  8.        Witamy w Lorem ipsum dolor sit amet,  consectetuer adipiscing elit. Cras ligula. Cras eu sapien. Maecenas
  9.        dignissim elit non dui interdum cursus. Nam sit amet velit vel dolor adipiscing tristique. Cras
  10.        elementum ultricies felis. <img src="img.jpg" align="right" style="float: right; margin-top: 5px;
  11.        margin-left: 3px;">Donec at risus quis nisl egestas nonummy. In augue. Maecenas tempor,
  12.        leo ut bibendum convallis, odio mauris rhoncus leo, a viverra libero odio vitae lorem. In id lacus.
  13.        Ut non ante ac nisl bibendum blandit. Maecenas varius dolor in ligula. Vivamus dapibus suscipit mi.
  14.        Proin fermentum augue non sem. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
  15.        inceptos hymenaeos. Proin quis urna. Nunc in magna. Fusce eget lectus.<br />
  16.        <br />
  17.        Nam quam. Proin fermentum convallis nunc. Praesent dapibus ligula eget turpis. Phasellus a libero
  18.        non sem tincidunt posuere. Etiam congue massa. Mauris odio. Pellentesque lorem. Vestibulum sem ipsum,
  19.        tempor sit amet, sagittis at, viverra quis, pede. Sed quis sem. Curabitur vitae mi id tellus vulputate
  20.        luctus. Quisque non risus eu dolor aliquet blandit. Phasellus ipsum velit, commodo nec, tristique et,
  21.        consectetuer sit amet, diam.<br />
  22.        <br />
  23.    </content>
  24. </index>

Zastosowanie:
  1. <?php
  2. $startXML = new XML( 'resource.xml' );
  3.  
  4. echo $startXML -> getContent( 'page' ) .'<br />';
  5.  
  6. if( $startXML -> getAttributes( 'mail', 'antispam' ) == 'yes' )
  7. {
  8. echo str_replace( '@', '[at]', $startXML -> getContent( 'mail' ) );
  9. }
  10. else
  11. {
  12. echo $startXML -> getContent( 'mail' );
  13. }
  14. ?>

Wlasnie taki parser, byl mi potrzebny do jednej strony, bardzo prosty przykład, prosta klasa, jesli bedzie rozbudowywana to takze opublikuje ja.

Ten post edytował kicaj_ 26.06.2005, 22:40:08


--------------------
PHP Developer

"Nadmiar wiedzy jest równie szkodliwy jak jej brak" Émile Zola
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi (1 - 6)
dado
post
Post #2





Grupa: Zarejestrowani
Postów: 194
Pomógł: 2
Dołączył: 12.04.2004
Skąd: Częstochowa

Ostrzeżenie: (10%)
X----


przy zastosowaniu pod php4 wyskakuje taki bat:

  1. Fatal error: Call to undefined function: __construct() in c:\apache\htdocs\last\xml\class2.xml.php on line 8
Go to the top of the page
+Quote Post
Speedy
post
Post #3





Grupa: Zarejestrowani
Postów: 651
Pomógł: 28
Dołączył: 4.12.2004

Ostrzeżenie: (0%)
-----


W php4 nazwa konstruktora jest taka sama jak nazwa klasy, w której on się znajduje. Nazwa __construct występuje tylko w php5. Poza tym, w kodzie są chyba komentarze dotyczące tego, dla której wersji jest odpowiednia funkcja.
Zresztą taka klasa będzie przydatna przede wszystkim dla php4, gdyż w php5 jest przecież simplexml winksmiley.jpg.


--------------------
Sygnatura niezgodna z regulaminem.
Go to the top of the page
+Quote Post
kriqs
post
Post #4





Grupa: Zarejestrowani
Postów: 148
Pomógł: 0
Dołączył: 31.05.2006

Ostrzeżenie: (0%)
-----


Witam
moim zdaniem smile.gif, ta classa jest bez sensu gdyż majac taki plik xml
Kod
<? xml version="1.1" encoding="ISO-8859-2" ?>

<index>
<cze>
  <mail antispam="cos">mail</mail>  
</cze>
<cze2>
  <mail antispam="yes">jakis inny</mail>  
</cze2>
</index>


niebardzo da sie wyciagnac ten drugi mail, no chyba ze sie da a ja nie wiem smile.gif.

Pozdrawiam


--------------------
Pozdrawiam
kriqs

mam nadzieje ze pomoglem :)
Go to the top of the page
+Quote Post
Lisek54
post
Post #5





Grupa: Zarejestrowani
Postów: 112
Pomógł: 0
Dołączył: 6.12.2004
Skąd: Miastko

Ostrzeżenie: (0%)
-----


Witam,

Albo również nie potrafię obslugiwać tej klasy albo nie ma tak dużych możliwości :-) Ten sam problem co kriqs.

Bardzo prosił bym o rozwiązanie naszego problemu.


--------------------
MP3: Ocean, Bracia, DKA, Arash, Energy
Warsztat: Apache2, PHP4, MySql, Linux Mandriva/Microsoft Windows XP
Zajęcia: Administrator serwera UT, prowadzenie kilku stron, pisanie małych skryptów dla rozrywki...
Cytat: "Co by człowiek chciał to zajęte..." - Kolega z ławki
Go to the top of the page
+Quote Post
cadavre
post
Post #6





Grupa: Zarejestrowani
Postów: 472
Pomógł: 7
Dołączył: 7.12.2005
Skąd: Gliwice

Ostrzeżenie: (0%)
-----


Jeśli chodzi o treść znaczników to można zrobić to np. tak:
  1. <?php
  2. function getContent( $strTagName )
  3. {
  4. preg_match_all( '|<'. $strTagName .'(.*)>(.*)</'. $strTagName .'>|isU', $this -> resFileContent, $arrContentTags );
  5.  
  6. for( $intIterTags = 0; $intIterTags < count( $arrContentTags[0] ); $intIterTags++ )
  7. {
  8. $return[] = $arrContentTags[2][$intIterTags];
  9. }
  10. return $return;
  11. }
  12. ?>

Wtedy
  1. <?php
  2. $xml = new XML('plik.xml');
  3. $data = $xml->getContent('mail');
  4. ?>

$data jest arrayem. Można returnować obiekt (jak w przypadku SimpleXML'a).

EDIT: Atrybuty załatwiłem tak:
  1. <?php
  2. function getAttributes( $strTagName, $strAttributeName )
  3. {
  4. preg_match_all( '|<'. $strTagName .'(.*)>(.*)</'. $strTagName .'>|isU', $this -> resFileContent, $arrContentTags );
  5.  
  6. for( $intIterTags = 0; $intIterTags < count( $arrContentTags[1] ); $intIterTags++ )
  7. {
  8. if( !empty( $arrContentTags[1][$intIterTags] ) )
  9. {
  10. $arrContentAttributes = explode( ' ', $arrContentTags[1][$intIterTags] );
  11.  
  12. array_shift( $arrContentAttributes );
  13.  
  14. for( $intIterAttributes = 0; $intIterAttributes < count( $arrContentAttributes ); $intIterAttributes++ )
  15. {
  16. $arrContentAttributesElements = explode( '=', $arrContentAttributes[$intIterAttributes] );
  17.  
  18. if( $arrContentAttributesElements[0] == $strAttributeName )
  19. {
  20. // Zabezpiecznie przed roznymi sposobami okreslenia wartosci atrybutow
  21. $arrDeleteQuotes[] = ''';
  22. $arrDeleteQuotes[] = '"';
  23.  
  24. $return[] = str_replace( $arrDeleteQuotes, '', $arrContentAttributesElements[1] );
  25. }
  26. }
  27. }
  28. else {
  29. $return[] = '';
  30. }
  31. }
  32. return $return;
  33. }
  34. ?>
Również otrzymujemy array - sprzężony z arrayem getContenta. Nie ma więc problemów z XMLem takim jak:
  1. <? xml version="1.1" encoding="ISO-8859-2" ?>
  2.  
  3. <index>
  4.   <page>Strona główna</page>
  5.   <author>kicaj_</author>
  6.   <mail>kicaj@m-cz.net</mail>
  7. </index>
  8. <index>
  9.   <page>Podstrona</page>
  10.   <author>cadavre</author>
  11.   <mail antispam="yes">cad@cad.pl</mail>
  12. </index>

Działają wtedy kolejne indeksy:
  1. <?php
  2. $test = new XML('plik.xml');
  3. $data = $test->getContent('mail');
  4. echo $data[1] . '<hr>';
  5. $data = $test->getAttributes('mail','antispam');
  6. echo $data[1];
  7. ?>


Pozdrawiam! smile.gif

kicaj - licencji tu nie widziałem więc pozwoliłem sobie na edycję. tongue.gif

Ten post edytował cadavre 31.12.2006, 14:26:50


--------------------
Silesian PHP User Group - www.spug.pl
Symfony2, OAuth2, budowanie API - masz pytania? Pisz!
Go to the top of the page
+Quote Post
lucgfx
post
Post #7





Grupa: Zarejestrowani
Postów: 1
Pomógł: 0
Dołączył: 3.08.2007

Ostrzeżenie: (0%)
-----


Mala poprawka do getContent, nie parsowal poprawnie tagow odrazu zamknietych.

  1. <?php
  2. function getContent( $strTagName )
  3. {
  4. preg_match_all( '|<'. $strTagName .'(.*)>(.*)</'. $strTagName .'>|isU', $this -> resFileContent, $arrContentTags );
  5.  
  6. for( $intIterTags = 0; $intIterTags < count( $arrContentTags[0] ); $intIterTags++ )
  7. {
  8. if ($arrContentTags[1][$intIterTags]==" /") 
  9. $return[] = '';
  10. else
  11. $return[] = $arrContentTags[2][$intIterTags];
  12. }
  13. return $return;
  14. }
  15. ?>
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 21.08.2025 - 12:31