Jump to content


Photo

Duvida - Xml No Php


  • Faça o login para participar
3 replies to this topic

#1 Leandro Camacho

Leandro Camacho

    Novato no fórum

  • Usuários
  • 4 posts
  • Sexo:Não informado
  • Localidade:Uberlandia - MG

Posted 15/02/2007, 12:36

Ola amigos,

Tenho um XML com a estrutura abaixo:

<?xml version="1.0" encoding="UTF-8" ?>
<Results xmlns:xsi="http://www.w3.org/20...chema-instance" xsi:noNamespaceSchemaLocation="XMLSearchResults.xsd">
<KeywordsRatingSet keywords="teste">
<Market>br</Market>
</KeywordsRatingSet>
<ResultSet id="searchResults" numResults="2" adultRating="G">
<Listing rank="1" title="Titulo 1" description="Descriçao 1" siteHost="www.dominio.com.br" biddedListing="true" adultRating="G">
<ClickUrl type="body">click.php?id=www.dominio.com.br</ClickUrl>
</Listing>
<Listing rank="2" title="Titulo 2" description="Descricao 2" siteHost="www.dominio2.com" biddedListing="true" adultRating="G">
<ClickUrl type="body">click.php?id=www.dominio2.com</ClickUrl>
</Listing>
<NextArgs>Keywords=teste&xargs=12KPjg12D6IFEzfGwicGpf9%5Fbz0</NextArgs>
</ResultSet>
</Results>


Como faço uma pagina em PHP que acessa esse XML e me traz os valores title, description, sitehost e clickurl no browser?
Ja tentei mecher com alguns parsers mas não consegui ainda nada. :-(

Desde já agradeço!

#2 Paulo André

Paulo André

    Why so serious?

  • Ex-Admins
  • 5114 posts
  • Sexo:Masculino
  • Localidade:Belo Horizonte - MG
  • Interesses:O.Q.F.J.?

Posted 06/03/2007, 10:49

Olá, dê uma olhada nesta parte do manual do PHP que tem uma ótima explicação e bons exemplos.

Flws....
(ok2)Até mais
Paulo André G Rodrigues,
ex-administrador Fórum WMO.


www.CanalDev.com.br

#3 Guilherme Blanco

Guilherme Blanco

    Loading...

  • Conselheiros
  • 891 posts
  • Sexo:Masculino
  • Localidade:São Carlos - SP/Brasil
  • Interesses:Programação Web e minha namorada (Maria Camila).

Posted 06/03/2007, 11:47

Você pode usar o leitor de XML que criei se quiser suporte a PHP4.

Não faz análise nem nada... tem outra finalidade, mas já faz o que vc quer.
Eis o código:

Arquivo class.AOP_XMLReader.php:
<?php

require_once "class.AOP_XMLElement.php";


class AOP_XMLReader
{
	var $_parser;
	var $_curEl;
	var $documentElement;


	function AOP_XMLReader()
	{
		$this->_curEl = null;

		$this->_parser = xml_parser_create();

		xml_set_object($this->_parser, $this);
		xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, 0);

		xml_set_element_handler($this->_parser, "_startElement", "_endElement");
		xml_set_character_data_handler($this->_parser, "_CDATAElement");
	}


	function & fromString($xmlContent)
	{
		$xmlReader = new AOP_XMLReader($xmlContent);
		return $xmlReader->_parse($xmlContent);
	}


	function & _parse($data)
	{
		if (!xml_parse($this->_parser, $data)) {
			$errMessage = xml_error_string(xml_get_error_code($this->_parser));
			$errLine = xml_get_current_line_number($this->_parser);

			xml_parser_free($this->_parser);

			die(sprintf("XML error: %s at line %d", $errMessage, $errLine));
		}

		xml_parser_free($this->_parser);

		return $this->documentElement;
	}


	function _startElement($parser, $tagName, $attrs)
	{
		$el = & new AOP_XMLElement($tagName);
		$el->setAttributes($attrs);
		$el->setParentNode($this->_curEl);

		if ($this->_curEl !== null) {
			$this->_curEl->addChildNode($el);
		} else {
			$this->documentElement = & $el;
		}

		$this->_curEl = & $el;
	}


	function _endElement($parser, $tagName)
	{
		if ($this->_curEl !== null) {
			if ($this->_curEl->getTag() != $tagName) {
				trigger_error(
					"<b>[Error]:</b> XML Node '" . $tagName . "' is not in the right inheritance!",
					E_USER_ERROR
				);
			}

			$this->_curEl = & $this->_curEl->getParentNode();
		}
	}


	function _CDATAElement($parser, $data)
	{
		if (strlen(trim($data)) > 0) {
			$cdata = & new AOP_XMLElement("#text");
			$cdata->setValue($data);
			$cdata->setParentNode($this->_curEl);

			$this->_curEl->addChildNode($cdata);
		}
	}
}

?>


Arquivo class.AOP_XMLElement.php:
<?php

class AOP_XMLElement
{
	var $tag;
	var $value;
	var $attributes;
	var $childNodes;
	var $parentNode;


	function AOP_XMLElement($tag = "")
	{
		if ($tag != "") {
			$this->setTag($tag);
		}
		
		$this->attributes = array();
		$this->childNodes = array();
	}
	
	
	function setTag($tag) { $this->tag = $tag; }


	function getTag() { return $this->tag; }


	function setValue($value) { $this->value = $value; }


	function getValue() { return $this->value; }
	

	function setParentNode(& $parent) { $this->parentNode = & $parent; }


	function & getParentNode() { return $this->parentNode; }


	function setAttributes($attrs) { $this->attributes = $attrs; }


	function getAttributes() { return $this->attributes; }
	

	function setAttribute($attrName, $attrValue)
	{
		$this->attributes[$attrName] = $attrValue;
	}
	

	function getAttribute($attrName) 
	{
		if ($this->hasAttribute($attrName)) {
			return $this->attributes[$attrName];
		}
		
		return null;
	}
	

	function hasAttribute($attrName)
	{
		if (array_key_exists($attrName, $this->attributes)) {
			return true;
		}

		return false;
	}
	

	function setChildNodes($nodes) { $this->childNodes = $nodes; }
	

	function & getChildNodes() { return $this->childNodes; }


	function addChildNode(& $node)
	{
		$this->childNodes[count($this->childNodes)] = & $node;
	}


	function & getChildNode($i)
	{
		if (array_key_exists($i, $this->childNodes)) {
			return $this->childNodes[$i];
		}
		
		return null;
	}
}

?>


Forma de uso:

<?php

require_once "class.AOP_XMLReader.php";

// Get file contents
$fContent = implode("", file("arquivo.xml"));

// Parse XML file into an array map
$XmlReader = AOP_XMLReader::fromString($fContent);

// Displaying contents
die("<pre>".print_r($XmlReader, true)."</pre>");

?>


Agora vc adapta este código pro seu uso pessoal. Se quiser adicionar uns créditos... agradeço.


[]s,
<script language="WebFórum">
// Dados:
Nome("Guilherme Blanco");
Localidade("São Carlos - SP/Brasil");
Cargo("Manutenção");
</script>

#4 JoneMello

JoneMello

    Novato no fórum

  • Usuários
  • 3 posts
  • Sexo:Não informado

Posted 30/03/2007, 03:19

acho que a sua resposta está aki
http://www.xml-training-guide.com/

ou mais especificamente aki
http://www.xml-train...xml-in-php.html

só tem um porém, está tudo em inglês. espero que ajude




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq