begin process at 2012 05 27 16:43:26
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Xml

 > ANALYSE XML, VALEURS COPIÉES DANS UNE CLASSE

ANALYSE XML, VALEURS COPIÉES DANS UNE CLASSE


 Information sur la source

Note :
9 / 10 - par 2 personnes
9,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Xml Niveau :Expert Date de création :17/07/2004 Vu / téléchargé :6 522 / 425

Auteur : GRenard

Ecrire un message privé
Site perso
Commentaire sur cette source (7)
Ajouter un commentaire et/ou une note

 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.

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Sources du même auteur

Source avec Zip Source avec une capture LECTURE/ÉCRITURE DE TAGS ID3 VERSION 1 ET VERSION 2
Source avec Zip GÉRER LES ÉCHAPPEMENTS DE CARACTÈRES SUR TABLEAUX MULTIDIMEN...
Source avec Zip Source avec une capture PROJECT SELECTOR (SÉLECTION FACILE DE PROJET AVEC APACHE) ET...
Source avec Zip Source avec une capture STATISTIQUES DE VOTRE PROJET (NOMBRE DE DOSSIERS, FICHIERS, ...
Source avec Zip Source avec une capture AFFICHAGE TABLEAU AVEC TEMPLATE CLASSE

 Sources de la même categorie

Source avec Zip JEU FRISE CHRONOLOGIQUE EN XML par mldvb
OBTENIR LES TAUX DE CHANGE DU JOUR EN EUROS par oallais
Source avec Zip AFFICHER LES FILM EN SALLE par slhuilli
Source avec Zip Source avec une capture MINI-PROCESSEUR XPROC (PIPELINE XML) par ordiman85
Source avec Zip Source avec une capture XML MAPPING TO CLASS OBJECTS / CHARGEMENT / PARSING / MODIFI... par aKheNathOn

Commentaires et avis

Commentaire de lcmartin le 21/08/2004 19:02:38

Bonjour,

Comment fait t on pour lire les "attributes" ?

<item ID="01" Nom="DUPOND" Prenom="Gérard">

je voudrais récupérer ID, Nom et Prenom, on fait comme sous XSL ?? c'est à dire : [...]['item']['@ID'] ?

une autre question : la balise root ne peut être lue ??

merci

Commentaire de GRenard le 29/09/2004 15:39:53

Pardon de ne pas avoir répondu plus vite, mais je n'ai jamais reçu de mail comme quoi quelqu'un avait écrit un commentaire.
Tu peux voir lors de la création du constructeur ceci
$xml_handler = new xml_page("attrib","data",TRUE,2);
Cela signifie que les data seront rangé dans ['data'] et les attributs dans ['attrib']. Ces valeurs peuvent être changée dans le constructeur.
Si tu veux récupérer les ID nom prenom de cette balise, tu n'as qu'à utiliser ensuite un regex ou preg.
La balise root peut être lu, il suffit de placer le 4ieme paramètre du constructeur à 0.

Si vous exécutez ce script directement, il se peut qu'il vous sorte des erreurs parce que PHPcs a changé comme ca pour s'amuser le format RSS de ces pages. Si vous prenez le fichier, -> no problem mais si vous prenez celui qui vient du web, vous devez changer en bas CREATOR par DC:CREATOR...

Commentaire de DieuLePer le 09/12/2004 23:45:47

Bonjour,

Ca fontionne avec PHP5 ca ?

Commentaire de GRenard le 10/12/2004 00:43:41

Peut-etre tu devrais lire ce qui est écrit : "Compatible PHP5 seulement."

Commentaire de DieuLePer le 10/12/2004 09:00:55

oups... désolé, je devais être fatigué hier soir, j'avais raté cette ligne :op

Disons qu'a force que tomber sur des scripts fait uniquement pour PHP4... j'avais plus d'espoir ! Bon, je teste ca !
CoOoOoOoL

:o)

Commentaire de GGPT le 31/01/2008 15:10:29 9/10

Bonjour,
Où faut-il mettre set_remplacement pour le cas où le XML contient plusieurs fois la même balise ?
Merci

Commentaire de julien__ le 21/04/2010 16:57:51

ça marche nikel mais j'ai un petit soucis avec mon fichier XML
il m'est fourni dans une structure qui ne fonctionne pas. Il faut que je rajoute <rss version="0.91"> et </rss> tout à la fin.

Seulement je ne veux pas le faire manuellement à chaque fois.

Est-ce que c'est possible de l'ajouter dans code source, pour qu'il fasse comme si il y avait ces deux balises au début et à la fin?

 Ajouter un commentaire




Nos sponsors


Sondage...

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,452 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales