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 landerbadi
      Boa tarde pessoal. Estou tentado fazer uma consulta no banco de dados porém estou tendo dificuldades. Tenho uma tabela chamada "itens" com os seguintes campos: id, item, ativo. Nela tem cadastrado vários itens. No campo ativo eu coloco a letra "S" para informar que este item está ativo no sistema. Por exemplo: 1, casa, S 2, mesa, S 3, cama, S 4, moto S 5, rádio O quinto registro "radio" não está ativo no sistema pois não tem um "S" no campo ativo. E outra tabela chamada "produtos" com os seguintes campos (id, item1, item2, item3) com os seguintes registros: 1, casa, mesa, moto 2, mesa, casa, cama 3, rádio, cama, mesa Eu preciso fazer uma busca na tabela produtos da seguinte maneira: Eu escolho um registro na tabela "itens", por exemplo "mesa". Preciso fazer com que o php me liste todos os registros da tabela "produtos" que contenham a palavra "mesa". Até aqui tudo bem eu consigo listar. Estou fazendo assim: <?php $item = "mesa" $sql = mysqli_query($conn, "SELECT * FROM produtos WHERE item1 LIKE '$item' OR item2 LIKE '$item' OR item3 LIKE '$item' LIMIT 10"); while($aux = mysqli_fetch_assoc($sql)) { $id = $aux["id"]; $item1 = $aux["item1"]; $item2 = $aux["item2"]; $item3 = $aux["item3"]; echo $id . " - " . $item1 . ", " . $item2 . ", " $item3 . "<br>"; } ?> O problema é que está listando todos os registros que contém o item mesa. Eu preciso que o php verifique os demais item e me liste somente os registro em que todos os registros estejam ativos no sistema. No exemplo acima ele não deveria listar o registro 3. pois nesse registro contém o item "radio" e este item não está ativo no sistema. Ou seja, o registro "radio" na tabela itens não possui um "S" na coluna "ativo". Alguém sabe como resolver isso?
    • Por ILR master
      Fala galera.
      Espero que todos estejam bem.
      Seguinte: Tenho um arquivo xml onde alguns campos estão com : (dois pontos), como o exemplo abaixo:
       
      <item>
      <title>
      d sa dsad sad sadasdas
      </title>
      <link>
      dsadas dsa sad asd as dsada
      </link>
      <pubDate>sadasdasdsa as</pubDate>
      <dc:creator>
      d sad sad sa ad as das
      </dc:creator>
      </item>
       
      Meu código:
       
      $link = "noticias.xml"; 
      $xml = simplexml_load_file($link); 
      foreach($xml -> channel as $ite) {     
           $titulo = $ite -> item->title;
           $urltitulo = $ite -> item->link;
           print $urltitulo = $ite -> item->dc:creator;
      } //fim do foreach
      ?>
       
      Esse campo dc:creator eu não consigo ler. Como faço?
       
      Agradeço quem puder me ajudar.
       
      Abs
       
       
    • Por First
      Olá a todos!
       
      Eu estou criando um sistema do zero mas estou encontnrando algumas dificuldades e não estou sabendo resolver, então vim recorrer ajuda de vocês.
      Aqui está todo o meu código: https://github.com/PauloJagata/aprendizado/
       
      Eu fiz um sistema de rotas mas só mostra o conteúdo da '/' não sei porque, quando eu tento acessar o register nada muda.
      E eu também quero que se não estiver liberado na rota mostra o erro de 404, mas quando eu tento acessar um link inválido, nada acontece.
      Alguém pode me ajudar com isso? E se tiver algumas sugestão para melhoria do código também estou aceitando.
       
       
      Desde já, obrigado.
    • Por landerbadi
      Olá pessoal, boa tarde
       
      Tenho uma tabela chamada "produtos" com os seguintes campos (id, produto) e outra tabela chamada "itens" com os seguintes campos (id, prod_01, prod_02, prod_03, prod_04).
       
      Na tabela produtos eu tenho cadastrado os seguintes produtos: laranja, maçã, uva, goiaba, arroz, feijão, macarrão, etc.
       
      Na tabela itens eu tenho cadastrado os itens da seguinte maneira:
       
      1, laranja, uva, arroz, feijão;
      2, maçã, macarrão, goiaba, uva;
      3, arroz, feijão, maçã, azeite
       
      Meu problema é o seguinte: 
      Eu escolho um produto da tabela "produtos", por exemplo "uva".  Preciso fazer uma consulta na tabela "itens" para ser listado todos os registros que contenham o produto "uva" e que todos os demais produtos estejam cadastrados na tabela "produtos".
       
      No exemplo acima seria listado apenas dois registros, pois o terceiro registro não contém o produto "uva". 
       
      Alguém pode me ajudar? Pois estou quebrando a cabeça a vários dias e não consigo achar uma solução.
×

Informação importante

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