Make a function that generates the XML string and not the XML itself PHP

Asked

Viewed 155 times

0

Hi, I’m trying to develop a function that generates only the XML string and not XML.

I am trying to connect on a Webservice that requires the following requirements:

user, password, passwordAgency and Xmlrequest.

The Xmlrequest are the parameters and methods I will call in the webservice

These 4 requirements I pass by soapcliente as follows:

array('usuarioCliente'=> $this->user,
      'senhaCliente'  => $this->password,
      'codigoAgencia' => $this->agencyCode,
      'xmlRequest' => $dados //parametros e metodos de todo o webservice
)

the problem is that the $data must go in XML string format, without appearing the 'xml version="1.0"' inside xmlRequest, if it appears the Webservice complains of the parameters and I am not able to develop a function that transforms the PHP keys into STRING XML

  • 1

    It would be good [Edit] the question and add the part you currently use to generate XML, then it is easier to help.

  • As it has to be the output of your XML string, exactly?

2 answers

3

Doing this doesn’t solve the case?

function convertXML($dados)
{
    $xml = new SimpleXMLElement('<tag_header/>');
    array_walk_recursive($dados, array ($xml, 'addChild'));
    $dados = preg_replace('/<\?xml(.*)>/', '', $xml->asXML());
    $return $dados;
}

$saida = array('usuarioCliente'=> $this->user,
      'senhaCliente'  => $this->password,
      'codigoAgencia' => $this->agencyCode,
      'xmlRequest' => convertXML($dados); 
);

0

Ivan, thank you!

But I’ve done a function that suits me just for what I need,

Follows the function I developed.

private function toXml($array, $xml=""){
    $xml = $xml;
    foreach ($array as $chave => $valor) {
        if(is_array($valor)){
            $xml .= "<".preg_replace( '/\d+$/', null, $chave ).">".$this->toXml($valor)."</".preg_replace( '/\d+$/', null, $chave ).">";
        }
        else{
            if($chave == 'dadoAdicional1' || $chave == 'dadoAdicional2'){
                if($valor==""){
                    $xml .= "<$chave/>";
                }
                else{
                    $xml .= "<$chave>".$valor."</$chave>";
                }
            }
            else{
                if($valor==""){
                    $xml .= "<$chave/>";
                }
                else{
                    $xml .= "<".preg_replace( '/\d+$/', null, $chave ).">".$valor."</".preg_replace( '/\d+$/', null, $chave ).">";
                }
            }
        }
    }   
    return $xml;    
}

I made a Regex to take the key numbers and added an exception for fields that should not be taken out the numbers.

Even so, thank you very much for your reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.