Accueil > > > ANALYSE XML, VALEURS COPIÉES DANS UNE CLASSE
ANALYSE XML, VALEURS COPIÉES DANS UNE CLASSE
Information sur la source
Description
Analyse XML et permet de copier les valeurs dans une classe pour ensuite générer un tableau (array) en PHP. Si par exemple votre XML contient plusieurs fois la même balise, il est fort probable que vos valeurs soient mises une à la suite des autres. Dans ce cas utilisez la fonction set_remplacement(). Exemple <item> <title>Somethi ng</title> </item> <item> <title>other</title> </i tem> Afin de ne pas avoir à la fin ['item']['title'] = "Somethingother", utilisez set_remplacement avec la $val 1, ce qui vous donnera [0]['title'] = "Something" et [1]['title'] = "other" Compatible PHP5 seulement.
Source
- <?php
- //////////////////////////////////////////////////////////////////////
- // index.php
- //--------------------------------------------------------------------
- //
- // Parse a XML file and put the information into a table.
- // If you know that an item will be repeated, you may use set_remplacement()
- // to avoid value being appended without any sense.
- //
- //--------------------------------------------------------------------
- // Revision History
- // V1.00 17 jul 2004 Jean-Sebastien Goupil
- //--------------------------------------------------------------------
- // Copyright (C) Jean-Sebastien Goupil
- // http://other.lookstrike.com/
- //--------------------------------------------------------------------
- //////////////////////////////////////////////////////////////////////
-
- class xml_page {
- private $xml_val = array();
- private $remplacement = array();
- private $attrib, $data, $auto_trim, $start_at;
-
- /**
- * @return void
- * @param string $attrib
- * @param string $data
- * @param bool $auto_trim
- * @param int $start_at
- * @desc Constructor, Attribute has $attrib key; Data has $data key, $auto_trim will trim data, $start_at depth starting recording.
- */
- function __construct($attrib,$data,$auto_trim=true,$start_at=0){
- $this->attrib = $attrib;
- $this->data = $data;
- $this->auto_trim = $auto_trim;
- $this->start_at = $start_at;
- }
-
- /**
- * @return void
- * @param string $key
- * @param int $val
- * @desc Create a remplacement for multiple items with same name. If $val==1 : 0,1,2; If $val==2 : ITEM0,ITEM1,ITEM2;
- */
- public function set_remplacement($key,$val){
- $this->remplacement[$key] = array('type'=>$val,'cur'=>0);
- }
-
- /**
- * @return string
- * @param string $val
- * @desc Return the right value (check if an element is duplicated (work with set_remplacement))
- */
- private function get_remplacement($val){
- if(isset($this->remplacement[$val]))
- return ($this->remplacement[$val]['type']==1)?$this->remplacement[$val]['cur']:$val.$this->remplacement[$val]['cur'];
- else
- return $val;
- }
-
- /**
- * @return void
- * @param string $element
- * @desc Increment the value for remplacement
- */
- public function close_element($element){
- if(isset($this->remplacement[$element]))
- $this->remplacement[$element]['cur']++;
- }
-
- /**
- * @return void
- * @param array $attrib
- * @param array $curDepth
- * @desc Create the array inside the other one and copy the attrib
- */
- public function add_element($attrib,$curDepth){
- $temp = &$this->add_attribs_sub($this->xml_val,$curDepth,$this->start_at);
- if(count($curDepth)>$this->start_at)
- $temp[$this->attrib] = &$attrib;
- }
-
- /**
- * @return void
- * @param string $data
- * @param array $curDepth
- * @desc Add data into the right array
- */
- public function add_data($data,$curDepth){
- $temp = &$this->add_attribs_sub($this->xml_val,$curDepth,$this->start_at);
- if(count($curDepth)>$this->start_at)
- if(!isset($temp[$this->data]))
- $temp[$this->data] = ($this->auto_trim)?trim($data):$data;
- else
- $temp[$this->data] .= ($this->auto_trim)?trim($data):$data;
- }
-
- /**
- * @return &array
- * @param array &$tab
- * @param array &$curDepth
- * @param int $i
- * @desc Return the last array supposed to be selected
- */
- private function &add_attribs_sub(&$tab,$curDepth,$i){
- $key = (isset($curDepth[$i]))?$this->get_remplacement($curDepth[$i]):NULL;
- if(isset($key))
- $temp = &$this->add_attribs_sub($tab[$key],$curDepth,$i+1);
- else
- $temp = &$tab;
- return $temp;
- }
-
- /**
- * @return array
- * @desc Return the value
- */
- public function get_xml(){
- return $this->xml_val;
- }
- }
-
- ///////////////////////////////////////////////////////////
- // FILE TO PARSE
- ///////////////////////////////////////////////////////////
- //$file = "rss.xml";
- $file = "http://www.phpcs.com/rss.aspx?type=code";
-
- $cur_depth = array();
-
- function startElement($parser, $name, $attrs)
- {
- global $cur_depth,$xml_handler;
- $cur_depth[count($cur_depth)] = $name;
- $xml_handler->add_element($attrs,$cur_depth);
- }
-
- function endElement($parser, $name)
- {
- global $cur_depth,$xml_handler;
- $xml_handler->close_element($name);
- unset($cur_depth[count($cur_depth)-1]);
- }
-
- function characterData($parser, $data)
- {
- global $cur_depth,$xml_handler;
- $xml_handler->add_data($data,$cur_depth);
- }
-
- ///////////////////////////////////////////////////////////
- // NEW OBJECT xml_page
- ///////////////////////////////////////////////////////////
- $xml_handler = new xml_page("attrib","data",true,2);
- // Will get 0, 1, 2... instead of ITEM key
- $xml_handler->set_remplacement("ITEM",1);
-
-
- ///////////////////////////////////////////////////////////
- // XML PARSING
- ///////////////////////////////////////////////////////////
- $xml_parser = xml_parser_create();
- xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
- xml_set_element_handler($xml_parser, "startElement", "endElement");
- xml_set_character_data_handler($xml_parser, "characterData");
- if (!($fp = fopen($file, "r"))) {
- die("Impossible de trouver le fichier XML");
- }
-
- while ($data = fread($fp, 4096)) {
- if (!xml_parse($xml_parser, $data, feof($fp))) {
- die(sprintf("XML Error : %s line %d",
- xml_error_string(xml_get_error_code($xml_parser)),
- xml_get_current_line_number($xml_parser)));
- }
- }
-
- xml_parser_free($xml_parser);
-
-
- ///////////////////////////////////////////////////////////
- // OTHER : DISPLAY
- ///////////////////////////////////////////////////////////
- $temp = $xml_handler->get_xml();
- $current = 0;
- while(isset($temp[$current])){
- echo "<a href=\"".$temp[$current]['LINK']['data']."\">".$temp[$current]['TITLE']['data']."</a> (sent by ".$temp[$current]['CREATOR']['data'].")<br>\n";
- $current++;
- }
- ?>
<?php
//////////////////////////////////////////////////////////////////////
// index.php
//--------------------------------------------------------------------
//
// Parse a XML file and put the information into a table.
// If you know that an item will be repeated, you may use set_remplacement()
// to avoid value being appended without any sense.
//
//--------------------------------------------------------------------
// Revision History
// V1.00 17 jul 2004 Jean-Sebastien Goupil
//--------------------------------------------------------------------
// Copyright (C) Jean-Sebastien Goupil
// http://other.lookstrike.com/
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
class xml_page {
private $xml_val = array();
private $remplacement = array();
private $attrib, $data, $auto_trim, $start_at;
/**
* @return void
* @param string $attrib
* @param string $data
* @param bool $auto_trim
* @param int $start_at
* @desc Constructor, Attribute has $attrib key; Data has $data key, $auto_trim will trim data, $start_at depth starting recording.
*/
function __construct($attrib,$data,$auto_trim=true,$start_at=0){
$this->attrib = $attrib;
$this->data = $data;
$this->auto_trim = $auto_trim;
$this->start_at = $start_at;
}
/**
* @return void
* @param string $key
* @param int $val
* @desc Create a remplacement for multiple items with same name. If $val==1 : 0,1,2; If $val==2 : ITEM0,ITEM1,ITEM2;
*/
public function set_remplacement($key,$val){
$this->remplacement[$key] = array('type'=>$val,'cur'=>0);
}
/**
* @return string
* @param string $val
* @desc Return the right value (check if an element is duplicated (work with set_remplacement))
*/
private function get_remplacement($val){
if(isset($this->remplacement[$val]))
return ($this->remplacement[$val]['type']==1)?$this->remplacement[$val]['cur']:$val.$this->remplacement[$val]['cur'];
else
return $val;
}
/**
* @return void
* @param string $element
* @desc Increment the value for remplacement
*/
public function close_element($element){
if(isset($this->remplacement[$element]))
$this->remplacement[$element]['cur']++;
}
/**
* @return void
* @param array $attrib
* @param array $curDepth
* @desc Create the array inside the other one and copy the attrib
*/
public function add_element($attrib,$curDepth){
$temp = &$this->add_attribs_sub($this->xml_val,$curDepth,$this->start_at);
if(count($curDepth)>$this->start_at)
$temp[$this->attrib] = &$attrib;
}
/**
* @return void
* @param string $data
* @param array $curDepth
* @desc Add data into the right array
*/
public function add_data($data,$curDepth){
$temp = &$this->add_attribs_sub($this->xml_val,$curDepth,$this->start_at);
if(count($curDepth)>$this->start_at)
if(!isset($temp[$this->data]))
$temp[$this->data] = ($this->auto_trim)?trim($data):$data;
else
$temp[$this->data] .= ($this->auto_trim)?trim($data):$data;
}
/**
* @return &array
* @param array &$tab
* @param array &$curDepth
* @param int $i
* @desc Return the last array supposed to be selected
*/
private function &add_attribs_sub(&$tab,$curDepth,$i){
$key = (isset($curDepth[$i]))?$this->get_remplacement($curDepth[$i]):NULL;
if(isset($key))
$temp = &$this->add_attribs_sub($tab[$key],$curDepth,$i+1);
else
$temp = &$tab;
return $temp;
}
/**
* @return array
* @desc Return the value
*/
public function get_xml(){
return $this->xml_val;
}
}
///////////////////////////////////////////////////////////
// FILE TO PARSE
///////////////////////////////////////////////////////////
//$file = "rss.xml";
$file = "http://www.phpcs.com/rss.aspx?type=code";
$cur_depth = array();
function startElement($parser, $name, $attrs)
{
global $cur_depth,$xml_handler;
$cur_depth[count($cur_depth)] = $name;
$xml_handler->add_element($attrs,$cur_depth);
}
function endElement($parser, $name)
{
global $cur_depth,$xml_handler;
$xml_handler->close_element($name);
unset($cur_depth[count($cur_depth)-1]);
}
function characterData($parser, $data)
{
global $cur_depth,$xml_handler;
$xml_handler->add_data($data,$cur_depth);
}
///////////////////////////////////////////////////////////
// NEW OBJECT xml_page
///////////////////////////////////////////////////////////
$xml_handler = new xml_page("attrib","data",true,2);
// Will get 0, 1, 2... instead of ITEM key
$xml_handler->set_remplacement("ITEM",1);
///////////////////////////////////////////////////////////
// XML PARSING
///////////////////////////////////////////////////////////
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
die("Impossible de trouver le fichier XML");
}
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML Error : %s line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
///////////////////////////////////////////////////////////
// OTHER : DISPLAY
///////////////////////////////////////////////////////////
$temp = $xml_handler->get_xml();
$current = 0;
while(isset($temp[$current])){
echo "<a href=\"".$temp[$current]['LINK']['data']."\">".$temp[$current]['TITLE']['data']."</a> (sent by ".$temp[$current]['CREATOR']['data'].")<br>\n";
$current++;
}
?>
Conclusion
Avec le code suivant, vous obtenez les nouveaux code sur phpCS.com adatpé à votre propre site. Si vous voulez tester le script mais vous ne pouvez pas ouvrir de fichier à distance avec fopen, vous pouvez prendre une copie de mon profil en RSS placé dans le ZIP (rss.xml). Vous pouvez aussi tester avec les code rss présent sur ce site par exemple, cela fonctionne très bien :) Pour mieux voir encore ce qu'il y a vraiment dans le tableau $temp à la fin du fichier, vous pouvez utiliser print_r($temp).
Vos commentaires sont les bienvenues.
Sources du même auteur
Sources de la même categorie
Commentaires et avis
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|