+ Reply to Thread
Results 1 to 4 of 4

Thread: Z XML do MySQL cez PHP

  1. #1

    Z XML do MySQL cez PHP

    Asi takto lahko by som charakterizoval svoj problem. Potrebujem vytvorit script ktory by vzal URL na ktorej sa nachadza nejake to XMLko napr. http://www.morezliav.sk/xml, rozlozi ho na jednotlive data a potom tie jednotlive data len vlozi do SQL query ktora sa vykona. Brusim po nete uz 14 hodin ale nenasiel som nic co by FUNCKCNE robilo to co potrebujem. Mam zatial len toto.
    Nejake to XMLko
    Code:
    <?xml version="1.0" encoding="Windows-1252"?>
     <InfoStreamResults Copyright="(c) 2006 Adfero Ltd." ArticleCount="49">
     
     <Article Created="14:40:07" ID="18253043">
     <Heading>This is the heading</Heading>
     <Date>21/08/2007</Date>
     <Contents><![CDATA[This is the data]]></Contents>
     <Categories>
     <Category ID="438008113">Environment</Category>
     </Categories>
     </Article>
    PHP script stiahnuty s netu
    Code:
    <?php 
    /** 
     * xml2array() will convert the given XML text to an array in the XML structure. 
     * Link: http://www.bin-co.com/php/scripts/xml2array/ 
     * Arguments : $contents - The XML text 
     *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
     *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance. 
     * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
     * Examples: $array =  xml2array(file_get_contents('feed.xml')); 
     *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
     */ 
    function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
        if(!$contents) return array(); 
    
        if(!function_exists('xml_parser_create')) { 
            //print "'xml_parser_create()' function not found!"; 
            return array(); 
        } 
    
        //Get the XML parser of PHP - PHP must have this module for the parser to work 
        $parser = xml_parser_create(''); 
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); 
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 
        xml_parse_into_struct($parser, trim($contents), $xml_values); 
        xml_parser_free($parser); 
    
        if(!$xml_values) return;//Hmm... 
    
        //Initializations 
        $xml_array = array(); 
        $parents = array(); 
        $opened_tags = array(); 
        $arr = array(); 
    
        $current = &$xml_array; //Refference 
    
        //Go through the tags. 
        $repeated_tag_index = array();//Multiple tags with same name will be turned into an array 
        foreach($xml_values as $data) { 
            unset($attributes,$value);//Remove existing values, or there will be trouble 
    
            //This command will extract these variables into the foreach scope 
            // tag(string), type(string), level(int), attributes(array). 
            extract($data);//We could use the array by itself, but this cooler. 
    
            $result = array(); 
            $attributes_data = array(); 
             
            if(isset($value)) { 
                if($priority == 'tag') $result = $value; 
                else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
            } 
    
            //Set the attributes too. 
            if(isset($attributes) and $get_attributes) { 
                foreach($attributes as $attr => $val) { 
                    if($priority == 'tag') $attributes_data[$attr] = $val; 
                    else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
                } 
            } 
    
            //See tag status and do the needed. 
            if($type == "open") {//The starting of the tag '<tag>' 
                $parent[$level-1] = &$current; 
                if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
                    $current[$tag] = $result; 
                    if($attributes_data) $current[$tag. '_attr'] = $attributes_data; 
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
    
                    $current = &$current[$tag]; 
    
                } else { //There was another element with the same tag name 
    
                    if(isset($current[$tag][0])) {//If there is a 0th element it is already an array 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                        $repeated_tag_index[$tag.'_'.$level]++; 
                    } else {//This section will make the value an array if multiple tags with the same name appear together 
                        $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array 
                        $repeated_tag_index[$tag.'_'.$level] = 2; 
                         
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                            unset($current[$tag.'_attr']); 
                        } 
    
                    } 
                    $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1; 
                    $current = &$current[$tag][$last_item_index]; 
                } 
    
            } elseif($type == "complete") { //Tags that ends in 1 line '<tag />' 
                //See if the key is already taken. 
                if(!isset($current[$tag])) { //New Key 
                    $current[$tag] = $result; 
                    $repeated_tag_index[$tag.'_'.$level] = 1; 
                    if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data; 
    
                } else { //If taken, put all things inside a list(array) 
                    if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array... 
    
                        // ...push the new element into that array. 
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result; 
                         
                        if($priority == 'tag' and $get_attributes and $attributes_data) { 
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                        } 
                        $repeated_tag_index[$tag.'_'.$level]++; 
    
                    } else { //If it is not an array... 
                        $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value 
                        $repeated_tag_index[$tag.'_'.$level] = 1; 
                        if($priority == 'tag' and $get_attributes) { 
                            if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well 
                                 
                                $current[$tag]['0_attr'] = $current[$tag.'_attr']; 
                                unset($current[$tag.'_attr']); 
                            } 
                             
                            if($attributes_data) { 
                                $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data; 
                            } 
                        } 
                        $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken 
                    } 
                } 
    
            } elseif($type == 'close') { //End of tag '</tag>' 
                $current = &$parent[$level-1]; 
            } 
        } 
         
        return($xml_array); 
    }
    A nakoniec subor kde to spustim

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>use</title>
    </head>
    
    <body>
    <?php include ('index.php'); ?>
    
    <?php
    $contents = file_get_contents('file.xml');//Or however you what it
    $result = xml2array($contents);
    print_r($result);
    ?>
    </body>
    </html>
    Problem je ze sa neviem pohnut dalej. Neviem s toho vybrat jednotlive udaje a vkladat ich do query. Musim priznat ze opacne to ide omnoho lahsie(MySQL - XML). Za kazdu radom budem vdacny
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

  2. #2
    Vdaka nemenovanemu Berankovy som sa posunul trochu dalej. Uz mam jednoduchu triedu na parsovanie presne tak ako by som ju potreboval. Vybera data s urcitych tagov a pracuje s nimi ako s jednotlivymi premennymi, cize ich mozem jednoduchu vlkladat do SQL. Problem je, nasledovny. Pouzivam nasledovny XML file na testovanie

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <FINANCE>
    <PRIJMY>
    <PRIJEM id="1">
    <NAZEV>
    Plat
    </NAZEV>
    <CASTKA>
    12000
    </CASTKA>
    </PRIJEM>
    <PRIJEM id="2">
    <NAZEV>
    Články na Linuxsoft
    </NAZEV>
    <CASTKA>
    3000
    </CASTKA>
    </PRIJEM>
    </PRIJMY>
    <VYDAJE>
    <VYDAJ id="1">
    <NAZEV>
    Byt
    </NAZEV>
    <CASTKA>
    4500
    </CASTKA>
    </VYDAJ>
    <VYDAJ id="2">
    <NAZEV>
    Jídlo
    </NAZEV>
    <CASTKA>
    2500
    </CASTKA>
    </VYDAJ>
    <VYDAJ id="3">
    <NAZEV>
    Koníčky
    </NAZEV>
    <CASTKA>
    1500
    </CASTKA>
    </VYDAJ>
    </VYDAJE>
    </FINANCE>
    Toto je trieda ktoru pouzivam na handlovanie toho XML.

    Code:
    <?php
      // nejdřív definice třídy
      class Parser
      {
        public $soubor;
        public $bilance = 0;
        public $priv_jeprijem = false;
        private $priv_znacka = "";
        private $priv_parser;
    	
    	private function startTag($parser, $nazev, $atributy)
        {
    		$this->priv_znacka = $nazev;
    		if($this->priv_znacka == "PRIJEM")
    		{
    			$this->priv_jeprijem = true;
    		}
    		if($this->priv_znacka == "VYDAJ")
    		{
    			$this->priv_jeprijem = false;
    		}
    	}
      
      	private function endTag($parser, $nazev) {}
        
        public function data($parser, $data)
        {
          if($this->priv_znacka == "CASTKA" && $this->priv_jeprijem)
    	  {
    		  $this->bilance += $data;
    	  }
          if($this->priv_znacka == "CASTKA" && !$this->priv_jeprijem)
    	  {
    		  $this->bilance -= $data;
    	  }
        }
        
        
       public function parse()
       {
          $this->priv_parser = xml_parser_create();
          xml_set_object($this->priv_parser, $this);
          xml_set_element_handler($this->priv_parser, "startTag", "endTag");
          xml_set_character_data_handler($this->priv_parser, "data");
          if(!($obsahsouboru = fopen($this->soubor, "r")))
    	  {
    		   die("Nemohu otevřít XML pro čtení.");
    	  }
          while($data = fread($obsahsouboru, 1024))
    	  {
    		   xml_parse($this->priv_parser, $data, feof($obsahsouboru));
    	  }
          xml_parser_free($this->priv_parser);
        }
      }
      
      // teď vlastní program
      $moje_bilance = new Parser;
      $moje_bilance->soubor = "./finance.xml";
      $moje_bilance->parse();
      echo $moje_bilance->bilance;
    ?>
    Skratka parada. Tento script normalne vstupuje medzi tagy CASTKA a ak sa tento tag nachadza medzi tagmi PRIJEM tak pripocita dane data k premennej bilancia ak sa tag CASTKA nachadza medzi VYDAJ tak odpocita data od bilancie. Vsetko super. Teraz je to vsak problem. Prejst od testovania k realnemu vyuzitiu. Potrebujem importovat XMLka v takomto formate

    http://www.morezliav.sk/xml


    Tak som si naivne myslel ze mi bude stacit do definicie premennych v triede dosadit vsetky premenne ktore potrebujem, cize public $id, public $city atd atd, a lahko zmodifikovat kod asi takto(priklad uvadzam len na tahanie ID nie na cele XML).

    Code:
    <?php
      // nejdřív definice třídy
      class Parser
      {
        public $soubor;
        public $bilance = 0;
        public $priv_jeprijem = false;
        private $priv_znacka = "";
        private $priv_parser;
    	
    	public $id;
    	
    	private function startTag($parser, $nazev, $atributy)
        {
    		$this->priv_znacka = $nazev;
    		if($this->priv_znacka == "DEAL")
    		{
    			$this->priv_jeprijem = true;
    		}
    		else
    		{
    			$this->priv_jeprijem = false;
    		}
    	}
      
      	private function endTag($parser, $nazev) {}
        
        public function data($parser, $data)
        {
          if($this->priv_znacka == "ID" && $this->priv_jeprijem)
    	  {
    		  $this->id = $data;
    	  }
          
        }
        
        
       public function parse()
       {
          $this->priv_parser = xml_parser_create();
          xml_set_object($this->priv_parser, $this);
          xml_set_element_handler($this->priv_parser, "startTag", "endTag");
          xml_set_character_data_handler($this->priv_parser, "data");
          if(!($obsahsouboru = fopen($this->soubor, "r")))
    	  {
    		   die("Nemohu otevřít XML pro čtení.");
    	  }
          while($data = fread($obsahsouboru, 1024))
    	  {
    		   xml_parse($this->priv_parser, $data, feof($obsahsouboru));
    	  }
          xml_parser_free($this->priv_parser);
        }
      }
      
      // teď vlastní program
      $moje_bilance = new Parser;
      $moje_bilance->soubor = "./produkty.xml";
      $moje_bilance->parse();
      echo $moje_bilance->id;
    ?>
    Avsak takyto kod nezobrazi vobec nic. Ja som nikdy s XMLkom nerobil ci sa uz jedna o Ajax alebo o PHPcko. Posledne dva dni som pochopil s prace s tymto jazykom strasne moc ale stale som len na zaciatku tak prosim pomozte ak viete. A ak neviete tak dajte aspon sucitny koment

    P.S. Este som zabudol povedat, ze to zatial riesim na urovni jedneho zaznamu. Este nemam ani paru ako to priesim ked tych zaznamov tam bude viac ako je to v hore uvedenom XMLku.

    EDIT: A neda sa mi pristupovat ani k jednotlivim castiam XMLka, ak triedu doplnim o public $nazov; a metodu data doplnim o
    Code:
    if($this->priv_znacka == "NAZEV" && $this->priv_jeprijem)
    	  {
    		  $this->nazov = $data;
    	  }
    a nakonci dam proste echo $moje_bilance->nazov; tak mi nic nevypise. Fakt nerozumiem ako toto cele funguje.
    Last edited by Werewolf; 15.06.2011 at 10:17.
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

  3. #3
    Tak ak nemáš s XML skúsenosti a potrebuješ to nejak rýchlo urobiť tak si to predsa preveď tou funkciou xml2array na pole s ktorým už v PHP vieš pracovať. Skúšal som to a tá funkcia je celkom schopná.

    Ešte som dnes narazil na toto: http://www.phpblog.sk/clanok/98/pars...-suboru-v-php/
    Všetci chcú vaše dobro. Nedajte si ho vziať!!

  4. #4
    Velmy pekne dakujem, strane mi pomohol clanok http://www.phpblog.sk/clanok/98/pars...-suboru-v-php/. Mas moj nekonecny vdak. Ked dokoncim cely projekt tak do Open sorce postnem celu parsovaciu triedu. Este raz dakujem
    Všetko o hrách a novinkách s herného sveta nájdete na http://the-guild.cz/.

+ Reply to Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts