За последние 24 часа нас посетили 38328 программистов и 1282 робота. Сейчас ищут 968 программистов ...

создание xml из класса

Тема в разделе "PHP для новичков", создана пользователем Slavka, 23 янв 2017.

  1. Slavka

    Slavka Активный пользователь

    С нами с:
    1 окт 2013
    Сообщения:
    722
    Симпатии:
    41
    Доброе время суток
    Ктонить работал с https://github.com/goetas-webservices/xsd2php

    ?

    с помошью этой штуки я создал класс .. ок это получилось

    PHP:
    1. class RequestType
    2. {
    3.  
    4.     /**
    5.      * @property string $oKATO
    6.      */
    7.     private $oKATO = null;
    8.    public function getOKATO()
    9.     {
    10.         return $this->oKATO;
    11.     }
    12.  
    13.     /**
    14.      * Sets a new oKATO
    15.      *
    16.      * @param string $oKATO
    17.      * @return self
    18.      */
    19.     public function setOKATO($oKATO)
    20.     {
    21.         $this->oKATO = $oKATO;
    22.         return $this;
    23.     }
    24. }
    ок.. работаем - забиваем .. получаем - все прекрасно .. кстати - он сделал еше 1 класс

    PHP:
    1. /**
    2. * Class representing Request
    3. */
    4. class Request extends RequestType
    5. {
    6.  
    7.  
    8. }
    через который и происходит вся работа


    далее мне надо создать xml

    я долго мучился .. и вот что собрал


    PHP:
    1. class XmlDomConstruct extends DOMDocument {
    2.  
    3.     /**
    4.      * Constructs elements and texts from an array or string.
    5.      * The array can contain an element's name in the index part
    6.      * and an element's text in the value part.
    7.      *
    8.      * It can also creates an xml with the same element tagName on the same
    9.      * level.
    10.      *
    11.      * ex:
    12.      * <nodes>
    13.      *   <node>text</node>
    14.      *   <node>
    15.      *     <field>hello</field>
    16.      *     <field>world</field>
    17.      *   </node>
    18.      * </nodes>
    19.      *
    20.      * Array should then look like:
    21.      *
    22.      * Array (
    23.      *   "nodes" => Array (
    24.      *     "node" => Array (
    25.      *       0 => "text"
    26.      *       1 => Array (
    27.      *         "field" => Array (
    28.      *           0 => "hello"
    29.      *           1 => "world"
    30.      *         )
    31.      *       )
    32.      *     )
    33.      *   )
    34.      * )
    35.      *
    36.      * @param mixed $mixed An array or string.
    37.      *
    38.      * @param DOMElement[optional] $domElement Then element
    39.      * from where the array will be construct to.
    40.      *
    41.      */
    42.     public function fromMixed($mixed, DOMElement $domElement = null) {
    43.  
    44.         $domElement = is_null($domElement) ? $this : $domElement;
    45.  
    46.         if (is_array($mixed)) {
    47.             foreach( $mixed as $index => $mixedElement ) {
    48.  
    49.                 if ( is_int($index) ) {
    50.                     if ( $index == 0 ) {
    51.                         $node = $domElement;
    52.                     } else {
    53.                         $node = $this->createElement($domElement->tagName);
    54.                         $domElement->parentNode->appendChild($node);
    55.                     }
    56.                 }
    57.              
    58.                 else {
    59.                     $node = $this->createElement($index);
    60.                     $domElement->appendChild($node);
    61.                 }
    62.              
    63.                 $this->fromMixed($mixedElement, $node);
    64.              
    65.             }
    66.         } else {
    67.             $domElement->appendChild($this->createTextNode($mixed));
    68.         }
    69.      
    70.     }
    71.  
    72. }

    в класс Request
    добавил функцию
    PHP:
    1. function get_vars(){
    2. $all = get_object_vars($this);
    3. return $all;
    а теперь самое интересное - как вы могли заметить в классе RequestType - все переменные private и за рамки класса они не выходят ..

    PHP:
    1. $dom = new XmlDomConstruct('1.0', 'utf-8');
    2. $dom->fromMixed($test->get_vars());
    3.  
    4. echo $dom->saveXML();
    кто подскажет как правильно после генерации классов генерировать xml
     
  2. anderstender

    anderstender Новичок

    С нами с:
    15 ноя 2016
    Сообщения:
    55
    Симпатии:
    25


    если я тебя правильно понял, то тебе нужно вывести все свойства, независимо от их области видимости?

    мне такая конструкция помогла


    Код (Text):
    1. class Test {
    2.  
    3.     public function __construct($a = 1, $b = 2, $c = 3){
    4.         $this->a = $a;
    5.         $this->b = $b;
    6.         $this->c = $c;
    7.     }
    8.  
    9.     private $a;
    10.     public $b;
    11.     protected $c;
    12.  
    13.     public function v(){
    14.         return get_object_vars($this);
    15.     }
    16. }
    17.  
    18.  
    19. class TestP extends Test{
    20.     private $d = 10;
    21.     public $e = 20;
    22.     protected $f = 30;
    23.  
    24.     public function v(){
    25.         $aParent = parent::v();
    26.         $aThis = get_object_vars($this);
    27.         return array_merge($aParent, $aThis);
    28.     }
    29. }
    30.  
    31.  
    32. $o = new TestP();
    33.  
    34. s::p($o->v());
    35.  
    36. /*
    37. s::p();  - это просто обертка над print_r()
    38. Array
    39. (
    40.     [e] => 20
    41.     [f] => 30
    42.     [a] => 1
    43.     [b] => 2
    44.     [c] => 3
    45.     [d] => 10
    46. )
    47. */
     
  3. romach

    romach Старожил

    С нами с:
    26 окт 2013
    Сообщения:
    2.904
    Симпатии:
    719
    Пример для раскуривания:

    PHP:
    1. <?php
    2.  
    3. class ParentTest {
    4.     private $parentPrivateProperty = 'parentPrivatePropertyValue';
    5. }
    6.  
    7. class Test extends ParentTest {
    8.     private $privateProperty = 'privateValue';
    9.     protected $protectedProperty = 'protectedValue';
    10.     public $publicProperty = 'publicValue';
    11. }
    12.  
    13. $object = new Test();
    14. $object->publicProperty = 'newPublicValue';
    15. $object->newProperty = ' netPropertyValue';
    16.  
    17. $reflection = new ReflectionObject($object);
    18. while ($reflection) {
    19.     echo $reflection->getName().PHP_EOL;
    20.     foreach ($reflection->getProperties() as $property) {
    21.         if ($property->isProtected() || $property->isPrivate()) {
    22.             $property->setAccessible(true);
    23.             echo $property->getName() . '[private]: ' . $property->getValue($object) . PHP_EOL;
    24.             $property->setAccessible(false);
    25.         } else {
    26.             echo $property->getName() . '[public]: ' . $property->getValue($object) . PHP_EOL;
    27.         }
    28.     }
    29.     echo 'Default properties:' . PHP_EOL;
    30.     foreach ($reflection->getDefaultProperties() as $name => $value) {
    31.         echo $name . ': ' . $value . PHP_EOL;
    32.     }
    33.     $reflection = $reflection->getParentClass();
    34. }
    Код (Text):
    1. Test
    2. privateProperty[private]: privateValue
    3. protectedProperty[private]: protectedValue
    4. publicProperty[public]: newPublicValue
    5. newProperty[public]:  netPropertyValue
    6. Default properties:
    7. privateProperty: privateValue
    8. protectedProperty: protectedValue
    9. publicProperty: publicValue
    10. ParentTest
    11. parentPrivateProperty[private]: parentPrivatePropertyValue
    12. Default properties:
    13. parentPrivateProperty: parentPrivatePropertyValue

    Доки: https://php.ru/manual/book.reflection.html
     
  4. Slavka

    Slavka Активный пользователь

    С нами с:
    1 окт 2013
    Сообщения:
    722
    Симпатии:
    41
    уф благодарю - теперь есть над чем подумать .. главное не забыть хорошо покурить