Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

fabiomco

Leitura de arquivo XML

Recommended Posts

Pessoal,

 

Estou com dificuldades de fazer a leitura de um arquivo XML utilizando PHP, e armazenar os valores do XML em um vetor, alguém pode me ajudar?

 

O resultado da leitura deste arquivo sempre retorna vazio, o que estou fazendo de errado?

<?php 
$url = 'http://sotelecom.cupomcampeao.com.br/allnations.xml';
$dom = new DOMDocument('1.0', 'utf-8');
$dom->load($url);

$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');

$elements = $xpath->query('//xs:element');
$produtos = $xpath->query('//Produtos');

echo "elements". $elements->length,PHP_EOL;
echo "products". $produtos->length;
echo "<br>"  ;

if (!is_null($produtos)) {
  foreach ($produtos as $produto) {
    $num++;
    $TIMESTAMP[$num]  = $produto->produtos->TIMESTAMP;
    $DEPARTAMENTO[$num]  = $produto->produtos->DEPARTAMENTO;
    $CATEGORIA[$num]  = $produto->produtos->CATEGORIA;

    echo "TIMESTAMP:". $TIMESTAMP[$num] ."<br>" ; 
  }
}
?> 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Como não tenho muito experiência e não faço muito uso do PHP, apenas converti meu interpretador e representador de XML em JavaScript para PHP para responder sua pergunta.

 

Contém apenas uma função que retornaria uma árvore (array) representativa da síntaxe do seu texto XML ($XMLAST). É bem simples de usar! Você tem que chamar a função e você vai ganhar a árvore.

 

Para fazer a leitura você irá fazer um loop infinito que irá quebrar em um momento, ele vai ficar interpretando a própria "Array", se o mesmo texto foi interpretado. A árvore representativa da síntaxe ajuda à ler muito bem.

 

Se você está enviando dados de usuário (que ele fez, por exemplo) é até importante fazer isso em alguns casos, pois ele pode digitar as coisas de qualquer maneira. Ex: "< div/ >..."

$XMLAST("<ClosedElement X="0" data-visible/><Container><Filho/></Container>")

Equivalente à esta array em JavaScript:

[
    {
        type:"Item",
        name:"ClosedElement",
        attributes:[
            {
                name:"X",
                value:"0"
            },
            {
                name:"data-visible",
                value:true
            }
        ]
    },
    {
        type:"List",
        name:"Container",
        attributes:[]
    },
    {
        type:"Item",
        name:"Filho",
        attributes:[]
    },
    {
        type:"End"
    }
]

Por incrível que pareça eu terminei ontem e está funcionando normal para PHP. Converti com uma ferramenta online. Tente usá-lo. :) Ele cria uma árvore em uma array específica com informações através de um texto XML.

<?php
$XMLAST = new Func(function($e = null) {
  for ($t = new Arr(), $a = new Object(), $n = new Object(), set($n, "path", -1.0), set($n, "textf", ""), set($n, "allowed", new Arr("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "@", "!", "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")), $r = new Func(function() use (&$a, &$n, &$t, &$e) {
    if (is(get($a, "textend"))) {
      if (is(get($a, "tag"))) {
        if (is(get($a, "tagname"))) {
          for (set($n, "length", get(get($n, "textf"), "length")), set($n, "tagname", ""), set($n, "i", 0.0); get($n, "length") > get($n, "i"); set($n, "i", 1, "+=", true)) {
            for (set($n, "cchar", call_method(get($n, "textf"), "charAt", get($n, "i"))), set($n, "b", 0.0); 66.0 > get($n, "b"); set($n, "b", 1, "+=", true)) {
              if (get($n, "cchar") === get(get($n, "allowed"), get($n, "b"))) {
                set($n, "tagname", get($n, "cchar"), "+=");
                break;
              }
            }
          }
          _seq(set($a, "tagname", not(1.0)), ">" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", new Arr())), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true)) : ((($and_ = "/" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", new Arr())), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true), set($n, "closureindex", call_method($e, "indexOf", ">")), $e = -1.0 === get($n, "closureindex") ? "" : call_method($e, "substring", get($n, "closureindex")), set($a, "tag", not(1.0))) : $and_)));
        } else if (is(get($a, "closuretagname"))) {
          if (is(_seq(set($a, "closuretagname", not(1.0)), set($a, "tag", not(1.0)), set($n, "closureindex", call_method($e, "indexOf", ">")), -1.0 !== get($n, "closureindex")))) {
            for ($e = call_method($e, "substring", get($n, "closureindex")), set($n, "parentitem", new Object("type", Object::$null)), set($n, "expectend", 0.0), set($n, "i", get($n, "path")); get($n, "i") > -1.0; set($n, "i", 1, "-=", true)) {
              if ("List" === get(get($t, get($n, "i")), "type")) {
                if (0.0 === get($n, "expectend")) {
                  set($n, "parentitem", get($t, get($n, "i")));
                  break;
                }
                set($n, "expectend", 1, "-=", true);
              } else {
                (($and_ = "End" === get(get($t, get($n, "i")), "type")) ? set($n, "expectend", 1, "+=", true) : $and_);
              }

            }
            _seq(set($n, "expectend", Object::$null), (($and_ = get($n, "textf") === get(get($n, "parentitem"), "name")) ? _seq(call_method($t, "push", new Object("type", "End")), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : $and_), set($n, "parentitem", Object::$null));
          }
        } else {
          for (set($n, "length", get(get($n, "textf"), "length")), set($n, "attrname", ""), set($n, "i", 0.0); get($n, "length") > get($n, "i"); set($n, "i", 1, "+=", true)) {
            for (set($n, "cchar", call_method(get($n, "textf"), "charAt", get($n, "i"))), set($n, "b", 0.0); 66.0 > get($n, "b"); set($n, "b", 1, "+=", true)) {
              if (get($n, "cchar") === get(get($n, "allowed"), get($n, "b"))) {
                set($n, "attrname", get($n, "cchar"), "+=");
                break;
              }
            }
          }
          _seq(call_method(get($n, "attributes"), "push", new Object("name", get($n, "attrname"), "value", not(0.0))), "=" === get($n, "curchar") ? _seq(set($n, "valueindex", call_method($e, "charAt", 1.0)), (($and_ = "\"" === get($n, "valueindex") || "'" === get($n, "valueindex")) ? _seq(set($n, "valuestart", call_method($e, "substring", 2.0)), -1.0 === set($n, "valuendindex", call_method(get($n, "valuestart"), "indexOf", get($n, "valueindex"))) ? _seq($e = "", set($a, "tag", not(1.0))) : _seq(set(get(get($n, "attributes"), to_number(get(get($n, "attributes"), "length")) - 1.0), "value", call_method(get($n, "valuestart"), "substring", 0.0, get($n, "valuendindex"))), $e = call_method($e, "substring", 2.0), $e = call_method($e, "substring", get($n, "valuendindex")))) : $and_)) : (">" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : ((($and_ = "/" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : $and_))));
        }


      } else {
        _seq(call_method($t, "push", new Object("type", "Text", "value", get($n, "textf"))), set($n, "path", 1, "+=", true));
      }

    } else {
      (is($and_ = get($a, "tag")) ? is(get($a, "tagname")) ? set($a, "tag", not(1.0)) : ("/" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0)), $e = call_method($e, "substring", 1.0), set($n, "closureindex", call_method($e, "indexOf", ">")), (($and1_ = -1.0 !== get($n, "closureindex")) ? $e = call_method($e, "substring", get($n, "closureindex")) : $and1_)) : ((($and1_ = ">" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true)) : $and1_))) : $and_);
    }

    set($a, "textend", not(1.0));
  }); ; ) {
    if (is(_seq(set($n, "curchar", call_method($e, "charAt", 0.0)), "" === get($n, "curchar")))) {
      call($r);
      break;
    }
    if ("<" === get($n, "curchar")) {
      if (is(_seq(call($r), set($a, "closuretagname", not(1.0)), "!--" === call_method($e, "substring", 1.0, 4.0)))) {
        if (is(_seq(set($a, "tag", not(1.0)), set($n, "closureindex", call_method($e, "indexOf", "-->")), call_method($t, "push", new Object("type", "Comment", "value", -1.0 === get($n, "closureindex") ? call_method($e, "substring", 4.0, get($e, "length")) : call_method($e, "substring", 4.0, get($n, "closureindex")))), set($n, "path", 1, "+=", true), -1.0 === get($n, "closureindex")))) {
          break;
        }
        $e = call_method($e, "substring", _plus(get($n, "closureindex"), 2.0));
      } else {
        _seq(set($a, "tag", not(0.0)), set($a, "tagname", not(0.0)), set($n, "attributes", new Arr()), set($n, "tagname", ""));
      }

    } else {
      not(get($a, "tag")) || "/" !== get($n, "curchar") && ">" !== get($n, "curchar") && "=" !== get($n, "curchar") && " " !== get($n, "curchar") && "\t" !== get($n, "curchar") ? is(get($a, "textend")) ? set($n, "textf", get($n, "curchar"), "+=") : _seq(set($n, "textf", get($n, "curchar")), set($a, "textend", not(0.0))) : ("/" === get($n, "curchar") ? is(get($a, "tagname")) && not(get($a, "textend")) ? _seq(set($a, "closuretagname", not(0.0)), set($a, "tagname", not(1.0)), set($a, "textend", not(1.0))) : ((is($and_ = get($a, "tag")) ? call($r) : $and_)) : (">" === get($n, "curchar") ? call($r) : ("=" === get($n, "curchar") ? call($r) : ((($and_ = " " === get($n, "curchar") || "\t" === get($n, "curchar")) ? call($r) : $and_)))));
    }

    $e = call_method($e, "substring", 1.0);
  }
  return _seq($a = Object::$null, $r = Object::$null, $e = Object::$null, $n = Object::$null, $t);
});

?>

Depois de implementar essa função, você pode chamá-la.

call_method($console, "log", get(get(call($XMLAST, "<div></div>"), 0.0), "name"));

PS: esqueci como mexer com arrays, então peguei essa linha pelo conversor.

Isso retorna o nome dessa div única no texto que você pode ver.

 

call($XMLAST, "<div></div>") - retorna uma array representativa do XML que é legível.

 

Nesse texto, "</div>" se tornaria um tipo "End" na array representativa.

 

Informações:

Tags abertas (ou listas que podem conter outros itens) são do tipo "List" e esperam pelo tipo "End";

Tags de fechamento (</tag>) são do tipo "End";

Tags fechadas (<tag/>) são do tipo "Item";

Comentários são do tipo "Comment";

Textos são do tipo "Text";

Toda tag tem a propriedade "attributes" onde estarão os atributos dela, mas em uma array. Cada atributo é um objeto com nome ("name") e valor ("value"). Sempre que um atributo é definido sem valor, então é só true.

 

O primeiro atributo seria pegado assim, por exemplo:

MeuXML[0]["attributes"][0]

(primeiro detecta se o que você passa é um "elemento" que pode conter atributos, tipo "List" ou "Item").

 

Para pegar o nome do primeiro atributo você faria algo como isso na sua árvore (array) representativa:

MeuXML[0]["attributes"][0]["name"]

Para ler os atributos é mais fácil usar um loop de 0 até o tamanho da lista de atributos. Nem pense em ir pegando um atributo sem saber se ele existe.

Compartilhar este post


Link para o post
Compartilhar em outros sites

HyDroper,

 

Coloquei o código que voce me passou no fonte do PHP (abaixo) e deu o erro na linha 34 :

 

Parse error: syntax error, unexpected '[' in on line 34 ($Produto[$num] = MeuXML[0]["produto"][0] ;)

<!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=iso-8859-1" /> 
<title>Import</title> 
</head>
 <body> 
 <h1>Import</h1> 
 <?php 


$url = 'http://sotelecom.cupomcampeao.com.br/allnations.xml';
$dom = new DOMDocument('1.0', 'utf-8');
$dom->load($url);


$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');


$elements = $xpath->query('//xs:element');
$produtos = $xpath->query('//Produtos');


echo "elements". $elements->length,PHP_EOL;
echo "products". $produtos->length;
echo "<br>"  ;

if (!is_null($produtos)) {
  foreach ($produtos as $produto) {
    $num++;

    call_method($console, "log", get(get(call($XMLAST, "<div></div>"), 0.0), "name"));

$Produto[$num]  = MeuXML[0]["produto"][0] ;
$TIMESTAMP[$num]  = MeuXML[0]["produto"][0]["TIMESTAMP"];
    $DEPARTAMENTO[$num]  =  MeuXML[0]["produto"][0]["DEPARTAMENTO"]; 
$DEPARTAMENTO[$num]  =  MeuXML[0]["produto"][0]["CATEGORIA"]; 

    echo $TIMESTAMP[$num];
  }
}

$XMLAST = new Func(function($e = null) {
  for ($t = new Arr(), $a = new Object(), $n = new Object(), set($n, "path", -1.0), set($n, "textf", ""), set($n, "allowed", new Arr("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "@", "!", "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")), $r = new Func(function() use (&$a, &$n, &$t, &$e) {
    if (is(get($a, "textend"))) {
      if (is(get($a, "tag"))) {
        if (is(get($a, "tagname"))) {
          for (set($n, "length", get(get($n, "textf"), "length")), set($n, "tagname", ""), set($n, "i", 0.0); get($n, "length") > get($n, "i"); set($n, "i", 1, "+=", true)) {
            for (set($n, "cchar", call_method(get($n, "textf"), "charAt", get($n, "i"))), set($n, "b", 0.0); 66.0 > get($n, "b"); set($n, "b", 1, "+=", true)) {
              if (get($n, "cchar") === get(get($n, "allowed"), get($n, "b"))) {
                set($n, "tagname", get($n, "cchar"), "+=");
                break;
              }
            }
          }
          _seq(set($a, "tagname", not(1.0)), ">" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", new Arr())), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true)) : ((($and_ = "/" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", new Arr())), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true), set($n, "closureindex", call_method($e, "indexOf", ">")), $e = -1.0 === get($n, "closureindex") ? "" : call_method($e, "substring", get($n, "closureindex")), set($a, "tag", not(1.0))) : $and_)));
        } else if (is(get($a, "closuretagname"))) {
          if (is(_seq(set($a, "closuretagname", not(1.0)), set($a, "tag", not(1.0)), set($n, "closureindex", call_method($e, "indexOf", ">")), -1.0 !== get($n, "closureindex")))) {
            for ($e = call_method($e, "substring", get($n, "closureindex")), set($n, "parentitem", new Object("type", Object::$null)), set($n, "expectend", 0.0), set($n, "i", get($n, "path")); get($n, "i") > -1.0; set($n, "i", 1, "-=", true)) {
              if ("List" === get(get($t, get($n, "i")), "type")) {
                if (0.0 === get($n, "expectend")) {
                  set($n, "parentitem", get($t, get($n, "i")));
                  break;
                }
                set($n, "expectend", 1, "-=", true);
              } else {
                (($and_ = "End" === get(get($t, get($n, "i")), "type")) ? set($n, "expectend", 1, "+=", true) : $and_);
              }


            }
            _seq(set($n, "expectend", Object::$null), (($and_ = get($n, "textf") === get(get($n, "parentitem"), "name")) ? _seq(call_method($t, "push", new Object("type", "End")), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : $and_), set($n, "parentitem", Object::$null));
          }
        } else {
          for (set($n, "length", get(get($n, "textf"), "length")), set($n, "attrname", ""), set($n, "i", 0.0); get($n, "length") > get($n, "i"); set($n, "i", 1, "+=", true)) {
            for (set($n, "cchar", call_method(get($n, "textf"), "charAt", get($n, "i"))), set($n, "b", 0.0); 66.0 > get($n, "b"); set($n, "b", 1, "+=", true)) {
              if (get($n, "cchar") === get(get($n, "allowed"), get($n, "b"))) {
                set($n, "attrname", get($n, "cchar"), "+=");
                break;
              }
            }
          }
          _seq(call_method(get($n, "attributes"), "push", new Object("name", get($n, "attrname"), "value", not(0.0))), "=" === get($n, "curchar") ? _seq(set($n, "valueindex", call_method($e, "charAt", 1.0)), (($and_ = "\"" === get($n, "valueindex") || "'" === get($n, "valueindex")) ? _seq(set($n, "valuestart", call_method($e, "substring", 2.0)), -1.0 === set($n, "valuendindex", call_method(get($n, "valuestart"), "indexOf", get($n, "valueindex"))) ? _seq($e = "", set($a, "tag", not(1.0))) : _seq(set(get(get($n, "attributes"), to_number(get(get($n, "attributes"), "length")) - 1.0), "value", call_method(get($n, "valuestart"), "substring", 0.0, get($n, "valuendindex"))), $e = call_method($e, "substring", 2.0), $e = call_method($e, "substring", get($n, "valuendindex")))) : $and_)) : (">" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : ((($and_ = "/" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0))) : $and_))));
        }




      } else {
        _seq(call_method($t, "push", new Object("type", "Text", "value", get($n, "textf"))), set($n, "path", 1, "+=", true));
      }


    } else {
      (is($and_ = get($a, "tag")) ? is(get($a, "tagname")) ? set($a, "tag", not(1.0)) : ("/" === get($n, "curchar") ? _seq(call_method($t, "push", new Object("type", "Item", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($n, "path", 1, "+=", true), set($a, "tag", not(1.0)), $e = call_method($e, "substring", 1.0), set($n, "closureindex", call_method($e, "indexOf", ">")), (($and1_ = -1.0 !== get($n, "closureindex")) ? $e = call_method($e, "substring", get($n, "closureindex")) : $and1_)) : ((($and1_ = ">" === get($n, "curchar")) ? _seq(call_method($t, "push", new Object("type", "List", "name", get($n, "tagname"), "attributes", get($n, "attributes"))), set($a, "tag", not(1.0)), set($n, "path", 1, "+=", true)) : $and1_))) : $and_);
    }


    set($a, "textend", not(1.0));
  }); ; ) {
    if (is(_seq(set($n, "curchar", call_method($e, "charAt", 0.0)), "" === get($n, "curchar")))) {
      call($r);
      break;
    }
    if ("<" === get($n, "curchar")) {
      if (is(_seq(call($r), set($a, "closuretagname", not(1.0)), "!--" === call_method($e, "substring", 1.0, 4.0)))) {
        if (is(_seq(set($a, "tag", not(1.0)), set($n, "closureindex", call_method($e, "indexOf", "-->")), call_method($t, "push", new Object("type", "Comment", "value", -1.0 === get($n, "closureindex") ? call_method($e, "substring", 4.0, get($e, "length")) : call_method($e, "substring", 4.0, get($n, "closureindex")))), set($n, "path", 1, "+=", true), -1.0 === get($n, "closureindex")))) {
          break;
        }
        $e = call_method($e, "substring", _plus(get($n, "closureindex"), 2.0));
      } else {
        _seq(set($a, "tag", not(0.0)), set($a, "tagname", not(0.0)), set($n, "attributes", new Arr()), set($n, "tagname", ""));
      }


    } else {
      not(get($a, "tag")) || "/" !== get($n, "curchar") && ">" !== get($n, "curchar") && "=" !== get($n, "curchar") && " " !== get($n, "curchar") && "\t" !== get($n, "curchar") ? is(get($a, "textend")) ? set($n, "textf", get($n, "curchar"), "+=") : _seq(set($n, "textf", get($n, "curchar")), set($a, "textend", not(0.0))) : ("/" === get($n, "curchar") ? is(get($a, "tagname")) && not(get($a, "textend")) ? _seq(set($a, "closuretagname", not(0.0)), set($a, "tagname", not(1.0)), set($a, "textend", not(1.0))) : ((is($and_ = get($a, "tag")) ? call($r) : $and_)) : (">" === get($n, "curchar") ? call($r) : ("=" === get($n, "curchar") ? call($r) : ((($and_ = " " === get($n, "curchar") || "\t" === get($n, "curchar")) ? call($r) : $and_)))));
    }


    $e = call_method($e, "substring", 1.0);
  }
  return _seq($a = Object::$null, $r = Object::$null, $e = Object::$null, $n = Object::$null, $t);
});


?> 
 </body>
 </html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Faça isso nessa linha e na anterior:

$MeuXML=call($XMLAST,"<div></div>");
$Produto[$num]=$MeuXML[0];//retorna a primeira lista "div"

Você tem que definir o $MeuXML com o que a função retorna, daí ele vai virar uma array.

PS::: você não tem nenhum elemento "produto", então vai ser "div" já que você está pegando o primeiro.

 

Para ter uma ideia...

$MeuXML=call($XMLAST,"SEU_XML_AQUI_OU_OUTRA_STRING_QUE_CONTÉM_XML");

Compartilhar este post


Link para o post
Compartilhar em outros sites

Coloquei o código, agora está dando erro na linha 25 Fatal error: Call to undefined function call() on line 25 ($MeuXML=call($XMLAST,$url);)

 

A função lê direto do do XML ? ($url = 'http://sotelecom.cupomcampeao.com.br/allnations.xml';)

 

 

<!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=iso-8859-1" /> 
<title>Import</title> 
</head>
 <body> 
 <h1>Import</h1> 
 <?php 


$url = 'http://sotelecom.cupomcampeao.com.br/allnations.xml';
$dom = new DOMDocument('1.0', 'utf-8');
$dom->load($url);


$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');


$elements = $xpath->query('//xs:element');
$produtos = $xpath->query('//Produtos');


echo "elements". $elements->length,PHP_EOL;
echo "products". $produtos->length;
echo "<br>"  ;


$MeuXML=call($XMLAST,$url);


    call_method($console, "log", get(get(call($XMLAST, "<div></div>"), 0.0), "name"));
    
if (!is_null($produtos)) {
  foreach ($produtos as $produto) {
    $num++;
    $Produto[$num]=$MeuXML[0];//retorna a primeira lista "div"
    echo $Produto[$num];
  }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Man, você está chamando a função console.log de JS do meu exemplo, tira ela.

 

Remova a linha:

call_method($console, "log", get(get(call($XMLAST, "<div></div>"), 0.0), "name"));

Então muda a linha:

$MeuXML=call($XMLAST,$url);

Para:

$MeuXML=get(call($XMLAST,"<!--AVISO: coloque o conteúdo do URL do XML em vez dessa string (texto)--><produto></produto>"));

também, defina a função do $XMLAST antes de ela ser usada, por exemplo, no topo do arquivo.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Fala galera, tudo bem?
       
      Tenho o seguinte codigo:
       
       class Data {
      public static function ExibirTempoDecorrido($date)
      {
          if(empty($date))
          {
              return "Informe a data";
          }
          $periodos = array("segundo", "minuto", "hora", "dia", "semana", "mês", "ano", "década");
          $duracao = array("60","60","24","7","4.35","12","10");
          $agora = time();
          $unix_data = strtotime($date);
          // check validity of date
          if(empty($unix_data))
          {  
              return "Bad date";
          }
          // is it future date or past date
          if($agora > $unix_data) 
          {  
              $diferenca     = $agora - $unix_data;
              $tempo         = "atrás";
          } 
          else 
          {
              $diferenca     = $unix_data - $agora;
              $tempo         = "agora";
          }
          for($j = 0; $diferenca >= $duracao[$j] && $j < count($duracao)-1; $j++) 
          {
              $diferenca /= $duracao[$j];
          }
          $diferenca = round($diferenca);
          if($diferenca != 1) 
          {
              $periodos[$j].= "s";
          }
          return "$diferenca $periodos[$j] {$tempo}";
      }
      }
       
      Funciona redondinho se o valor retornado for de algumas horas, mas...
      Quando passa de dois meses, ele retorna a palavra mess. Deve ser por conta dessa linha
      if($diferenca != 1) 
          {
              $periodos[$j].= "s";
          }
       
      Quero que modre:
       
      2 meses atrás
      e não
      2 mess atrás.
       
      Espero que tenham entendido.
       
      Valeu
    • Por Carlos Web Soluções Web
      Olá...
      Estou tentando fazer o seguinte !!
      Listando dados em tabela !!
      Gostaria que....se na listagem houver 4 linhas...indepedente de seu número de ID, faça a listagem em ID ser em ordem 1 2 3 4 !!
      Exemplo...se tiver uma listagem de dados que está em ID 1 3 3...faça ficar 1 2 3 !!

       
      echo "<table class='tabela_dados' border='1'> <tr> <td>ID</td> <td>Nome Empresa</td> <td>Responsável</td> <td>Telefone 1</td> <td>Telefone 2</td> <td>E-mail 1</td> <td>E-mail 2</td> <td>Endereço</td> <td>CEP</td> <td>Bairro</td> <td>AÇÃO 1</td> <td>AÇÃO 2</td> </tr> "; $sql = "SELECT ID FROM usuarios_dados WHERE Usuario='$usuario'"; $result = $conn->query($sql); $num_rows = $result->num_rows; $Novo_ID = 1; for ($i = 0; $i < $num_rows; $i++) { $registro = $result -> fetch_row(); $sql2 = "UPDATE usuarios_dados SET ID='$Novo_ID' WHERE ID='$Novo_ID'"; $result2 = $conn->query($sql2); $Novo_ID++; } $sql = "SELECT * FROM usuarios_dados"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<tr> <td>$row[ID]</td> <td>$row[Nome_Empresa]</td> <td>$row[Responsavel]</td> <td>$row[Telefone_1]</td> <td>$row[Telefone_2]</td> <td>$row[Email_1]</td> <td>$row[Email_2]</td> <td>$row[Endereço]</td> <td>$row[CEP]</td> <td>$row[Bairro]</td> <td> <form method='post' action='Editar_Dados.php'> <input type='hidden' name='usuario' value='$usuario'> <input type='hidden' name='senha' value='$senha'> <input type='hidden' name='ID' value='$row[ID]'> <input type='submit' style='padding: 10px;' value='EDITAR'> </form> </td> <td> <form method='post' action='Deletar_Dados.php'> <input type='hidden' name='usuario' value='$usuario'> <input type='hidden' name='senha' value='$senha'> <input type='hidden' name='ID' value='$row[ID]'> <input type='submit' style='padding: 10px;' value='DELETAR'> </form> </td> </tr> "; } } else { echo "0 results"; } $conn->close();  
    • Por ILR master
      Boa tarde pessoal, tudo bem ?
       
      Eu uso o tinymce para cadastro de textos no meu siite, porém, quero fazer um sistema para que os colunistas possam fazer o próprio post.
      O problema do tinymce, é que ele mantém a formatação do texto copiado, como tamanho de fonts, negritos, etc... Quero que o usuário cole o texto e a própria textarea limpe a formatação para que ele formate como quiser.
       
      A pergunta é:
       
      O tinymce tem uma opção para desabilitar a formatação quando um texto é colocado?
      Tem alguma função via java ou php para retirar a formatação assim que o texto é colado?
      Ou é melhor usar um outro editor?
       
      Agradeço deste já.
    • Por Giovanird
      Olá a todos!
      Tenho uma pagina que possui uma DIV onde coloquei uma pagina PHP.
      Uso a função setInterval para atualizar a pagina inclusa dentro da DIV.
      O problema é que ao acessar o site , a DIV só me mostra a pagina inclusa somente quando completo o primeiro minuto.
      Preciso que a pagina inclusa já inicie carregada
       
      Meu código JavaScript e a DIV com a pagina PHP
       
      <script> function atualiza(){ var url = 'direita.php'; $.get(url, function(dataReturn) { $('#direita').html(dataReturn); }); } setInterval("atualiza()",60000); </script> <div> <span id="direita"></span> </div>  
    • Por ILR master
      Fala pessoal.
       
      Seguinte:
       
      Quero selecionar duas tabelas e mostrar com resultados intercalados. Abaixo segue um código explicando para vcs terem uma ideia.
       
      $consulta = "SELECT A.*, B.* FROM tabela1 A, tabela2 B'";
      $resultado = mysqli_query($conexao, $consulta) or die ("erro");
      while($busca = mysqli_fetch_array($resultado)){
       
      print $busca['cod_evento']; --> traz o código da tabela1 
      print $busca['titulo_evento']; -->  traz o titulo da tabela1
      print $busca['cod_noticia']; --> traz o código da tabela2
      print $busca['titulo_noticia']; --> traz o tituloda tabela2
       
      }
       
      Espero que entendam. Grato
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.