Convert xml to array or json in php

2

Can you please help me to convert some data that I have in xml to json or to an array in PHP?

This xml I consume it from a web service and when using a var_dump or echo I confirm that I do have an answer and the data that I require, however, to work with that data in an array or json, no information appears.

The function with which I consume the web service is:

function consultaServicioWeb($cedula) {

$url='http://...';

$credentials = "...";   

$data_string='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://.../">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:getFichaGeneral>
         <!--Optional:-->
         <codigoPaquete>...</codigoPaquete>
         <!--Optional:-->
         <numeroIdentificacion>'.__.'</numeroIdentificacion>
      </ser:getFichaGeneral>
   </soapenv:Body>
</soapenv:Envelope>'; 

$ch = curl_init($url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);     
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/xml;charset=UTF-8',  
    'Authorization: Basic ' . base64_encode($credentials))                                                                       
);                                                                                                                   

$post = curl_exec($ch);

if ($post) {

    echo "1)xml-->>";
    var_dump($post);

    $xml = simplexml_load_string($post);
    echo "\n\n 2)simplexml_load_string-->>";
    var_dump($xml);

    $json = json_encode($xml);
    echo "\n\n 3)json-->>";
    var_dump($json);


    $array = json_decode($json,TRUE);
    echo "\n\n 4)array-->>";
    var_dump($array);

return json_encode($array);

} else {
    $responce = new stdClass();
$responce->mensaje ='FALLA EN LA CONEXION A LA CONSULTA NO SE ENCUENTRA DISPONIBLE...!!!';
return json_encode($responce);
}


}

The result obtained from var_dump is:

    1)xml-->>string(2029) "<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:getFichaGeneralResponse xmlns:ns2="http://__/">
         <return>
            <codigoPaquete>198</codigoPaquete>
            <instituciones>
               <datosPrincipales>
                  <registros>
                     <campo>cedula</campo>
                     <codigo>1</codigo>
                     <valor>__</valor>
                  </registros>
                  <registros>
                     <campo>nombre</campo>
                     <codigo>2</codigo>
                     <valor>BUENAÑO RODRIGUEZ CARLOS DAVID</valor>
                  </registros>
                  <registros>
                     <campo>genero</campo>
                     <codigo>3</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>condicionCiudadano</campo>
                     <codigo>4</codigo>
                     <valor>CIUDADANO</valor>
                  </registros>
                  <registros>
                     <campo>fechaNacimiento</campo>
                     <codigo>5</codigo>
                     <valor>04/11/1986</valor>
                  </registros>
                  <registros>
                     <campo>lugarNacimiento</campo>
                     <codigo>6</codigo>
                     <valor>PICHINCHA/QUITO/SAN BLAS</valor>
                  </registros>
                  <registros>
                     <campo>nacionalidad</campo>
                     <codigo>7</codigo>
                     <valor>ECUATORIANA</valor>
                  </registros>
                  <registros>
                     <campo>estadoCivil</campo>
                     <codigo>8</codigo>
                     <valor>CASADO</valor>
                  </registros>
                  <registros>
                     <campo>conyuge</campo>
                     <codigo>10</codigo>
                     <valor>BOLAÑOS HERNANDEZ JESENIA LILIANA</valor>
                  </registros>
                  <registros>
                     <campo>domicilio</campo>
                     <codigo>15</codigo>
                     <valor>PICHINCHA/QUITO/CHAUPICRUZ</valor>
                  </registros>
                  <registros>
                     <campo>callesDomicilio</campo>
                     <codigo>16</codigo>
                     <valor>GRANDA CENTENDO SEBASTIAN CEDE</valor>
                  </registros>
                  <registros>
                     <campo>numeroCasa</campo>
                     <codigo>17</codigo>
                     <valor>OE5-130</valor>
                  </registros>
                  <registros>
                     <campo>fechaDefuncion</campo>
                     <codigo>20</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>fechaInscripcionDefuncion</campo>
                     <codigo>39</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>instruccion</campo>
                     <codigo>558</codigo>
                     <valor>SUPERIOR</valor>
                  </registros>
                  <registros>
                     <campo>profesion</campo>
                     <codigo>563</codigo>
                     <valor>ESTUDIANTE</valor>
                  </registros>
                  <registros>
                     <campo>sexo</campo>
                     <codigo>1328</codigo>
                     <valor>HOMBRE</valor>
                  </registros>
               </datosPrincipales>
               <nombre>Registro Civil</nombre>
            </instituciones>
         </return>
      </ns2:getFichaGeneralResponse>
   </soap:Body>
</soap:Envelope>"


 2)simplexml_load_string-->>object(SimpleXMLElement)#3 (0) {
}


 3)json-->>string(2) "{}"


 4)array-->>array(0) {
}

Thank you very much for your contributions.

    
asked by David B 15.12.2016 в 20:36
source

4 answers

1

Another way could be using XML Parser

Assuming the following structure for each "record"

<campo>X</campo>
<codigo>Y</codigo>
<valor>Y</valor>

We can parse the XML like this:

$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $post, $valores, $indices);
xml_parser_free($parser);

$datos = array();
// Iteramos todos los tags campos
foreach ($indices['campo'] as $idx => $posicion) {
    // Sabemos que tag de promedio esta el tag "valor"
    $datos[trim($valores[$posicion]['value'])] = trim($valores[$posicion + 2]['value']);
}

print_r($datos);

The result would be:

Array
(
    [cedula] => __
    [nombre] => BUENAÑO RODRIGUEZ CARLOS DAVID
    [genero] => 
    [condicionCiudadano] => CIUDADANO
    [fechaNacimiento] => 04/11/1986
    [lugarNacimiento] => PICHINCHA/QUITO/SAN BLAS
    [nacionalidad] => ECUATORIANA
    [estadoCivil] => CASADO
    [conyuge] => BOLAÑOS HERNANDEZ JESENIA LILIANA
    [domicilio] => PICHINCHA/QUITO/CHAUPICRUZ
    [callesDomicilio] => GRANDA CENTENDO SEBASTIAN CEDE
    [numeroCasa] => OE5-130
    [fechaDefuncion] => 
    [fechaInscripcionDefuncion] => 
    [instruccion] => SUPERIOR
    [profesion] => ESTUDIANTE
    [sexo] => HOMBRE
)

Demo here

    
answered by 15.12.2016 в 22:30
0

Try the following, where the variable $response is the full string of your XML.

$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//soapBody');
$array = json_decode(json_encode((array)$body), TRUE); 
foreach ($array[0]['ns2getFichaGeneralResponse']['return']['instituciones']['datosPrincipales']['registros'] as $key => $value) {
   print_r($value['campo'] . "----" . $value['codigo'] . "----" . $value['valor']);
   print_r("<br>");
}  

You will get something like that, in some cases you will see a Notice and it is because in some cases valor is an arrangement, there you should see how you occupy those fields:

cedula-- --1-- --__
nombre-- --2-- --BUENAÑO RODRIGUEZ CARLOS DAVID

Notice: Array to string conversion in C: \xampp\ htdocs\ prueba\ index.php on line 135
genero-- --3-- --Array
condicionCiudadano-- --4-- --CIUDADANO
fechaNacimiento-- --5-- --04 / 11 / 1986
lugarNacimiento-- --6-- --PICHINCHA / QUITO / SAN BLAS
nacionalidad-- --7-- --ECUATORIANA
estadoCivil-- --8-- --CASADO
conyuge-- --10-- --BOLAÑOS HERNANDEZ JESENIA LILIANA
domicilio-- --15-- --PICHINCHA / QUITO / CHAUPICRUZ
callesDomicilio-- --16-- --GRANDA CENTENDO SEBASTIAN CEDE
numeroCasa-- --17-- --OE5 - 130

Notice: Array to string conversion in C: \xampp\ htdocs\ prueba\ index.php on line 135
fechaDefuncion-- --20-- --Array

Notice: Array to string conversion in C: \xampp\ htdocs\ prueba\ index.php on line 135
fechaInscripcionDefuncion-- --39-- --Array
instruccion-- --558-- --SUPERIOR
profesion-- --563-- --ESTUDIANTE
sexo-- --1328-- --HOMBRE
    
answered by 15.12.2016 в 22:01
0

Many thanks to all, unfortunately none of the answers worked correctly, however, thanks to the help of a friend I was able to solve it in the following way:

Create a new class:

<?php
//header('Content-Type: text/xml; charset=UTF-8'); 
/**
* XMLToArray Generator Class
* @author  :  MA Razzaque Rupom <[email protected]>, <rupom [email protected]>
*             Moderator, phpResource (LINK1http://groups.yahoo.com/group/phpresource/LINK1)
*             URL: LINK2http://www.rupom.infoLINK2
* @version :  1.0
* @date       06/05/2006
* Purpose  : Creating Hierarchical Array from XML Data
* Released : Under GPL
*/

class XmlToArray
{

    var $xml='';

    /**
    * Default Constructor
    * @param $xml = xml data
    * @return none
    */

    function XmlToArray($xml)
    {
       $this->xml = $xml;

    }

    /**
    * _struct_to_array($values, &$i)
    *
    * This is adds the contents of the return xml into the array for easier processing.
    * Recursive, Static
    *
    * @access    private
    * @param    array  $values this is the xml data in an array
    * @param    int    $i  this is the current location in the array
    * @return    Array
    */

    function _struct_to_array($values, &$i)
    {
        $child = array();
        if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);

        while ($i++ < count($values)) {
            switch ($values[$i]['type']) {
                case 'cdata':
                array_push($child, $values[$i]['value']);
                break;

                case 'complete':
                    $name = $values[$i]['tag'];
                    if(!empty($name)){
                    $child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
                    if(isset($values[$i]['attributes'])) {
                        $child[$name] = $values[$i]['attributes'];
                    }
                }
              break;

                case 'open':
                    $name = $values[$i]['tag'];
                    $size = isset($child[$name]) ? sizeof($child[$name]) : 0;
                    $child[$name][$size] = $this->_struct_to_array($values, $i);
                break;

                case 'close':
                return $child;
                break;
            }
        }
        return $child;
    }//_struct_to_array

    /**
    * createArray($data)
    *
    * This is adds the contents of the return xml into the array for easier processing.
    *
    * @access    public
    * @param    string    $data this is the string of the xml data
    * @return    Array
    */

    function createArray()
    {


        //$texto    = $this->xml;
                //$xml = $this->caracteres($texto);
                $xml    = $this->xml;
        $values = array();
        $index  = array();
        $array  = array();
                $parser= xml_parser_create();
                //echo utf8_encode($xml);
                //xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING,0); 
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parse_into_struct($parser, utf8_encode($xml), $values, $index);
        xml_parser_free($parser);
        $i = 0;
        $name = utf8_decode($values[$i]['tag']);
        $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
        $array[$name] = $this->_struct_to_array($values, $i);
        return $array;
    }//createArray

}//XmlToArray
?>

And my code stayed like this:

require_once "pg_gnr_ws_class_xmltoarray.php";

function consultaServicioWeb($cedula) {

    //$responce = new stdClass();

$url='http://___';

$credentials = "___";   

$data_string='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://___/">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:getFichaGeneral>
         <!--Optional:-->
         <codigoPaquete>___</codigoPaquete>
         <!--Optional:-->
         <numeroIdentificacion>'.$cedula.'</numeroIdentificacion>
      </ser:getFichaGeneral>
   </soapenv:Body>
</soapenv:Envelope>'; 

$ch = curl_init($url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);     
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/xml',  
    'Authorization: Basic ' . base64_encode($credentials))                                                                       
);                                                                                                                   

$post = curl_exec($ch);

if ($post) {



    $xmlObj=new XmlToArray($post);
    //Creating Array
    $arrayData = $xmlObj->createArray();

    $responce = new stdClass();

    $responce->cedula = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][0]["valor"];
    $responce->nombreRC = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][1]["valor"];
    $responce->genero = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][2]["valor"];
    $responce->condicionCiudadano = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][3]["valor"];
    $responce->fechaNacimientoRC = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][4]["valor"];
    $responce->lugarNacimiento = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][5]["valor"];
    $responce->nacionalidad = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][6]["valor"];
    $responce->estadoCivil = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][7]["valor"];
    $responce->conyuge = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][8]["valor"];
    $responce->domicilio = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][9]["valor"];
    $responce->callesDomicilio = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][10]["valor"];
    $responce->numeroCasa = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][11]["valor"];
    $responce->fechaDefuncion = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][12]["valor"];
    $responce->fechaInscripcionDefuncion = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][13]["valor"];
    $responce->instruccion = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][14]["valor"];
    $responce->profesion = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][15]["valor"];
    $responce->sexo = $arrayData["soap:Envelope"]["soap:Body"][0]["ns2:getFichaGeneralResponse"][0]["return"][0]["instituciones"][0]["datosPrincipales"][0]["registros"][16]["valor"];

    $responce->mensaje ='';


} else {
    $responce = new stdClass();
    $responce->mensaje ='FALLA EN LA CONEXION A LA CONSULTA, EL SERVICIO NO SE ENCUENTRA DISPONIBLE...!!!';

    }
    return json_encode($responce);

}

Getting the following result:

{"cedula":"___","nombreRC":"BUENA\u00d1O RODRIGUEZ CARLOS DAVID","genero":"","condicionCiudadano"
:"CIUDADANO","fechaNacimientoRC":"04\/11\/1986","lugarNacimiento":"PICHINCHA\/QUITO\/SAN BLAS","nacionalidad"
:"ECUATORIANA","estadoCivil":"CASADO","conyuge":"BOLA\u00d1OS HERNANDEZ JESENIA LILIANA","domicilio"
:"PICHINCHA\/QUITO\/CHAUPICRUZ","callesDomicilio":"GRANDA CENTENDO SEBASTIAN CEDE","numeroCasa":"OE5-130"
,"fechaDefuncion":"","fechaInscripcionDefuncion":"","instruccion":"SUPERIOR","profesion":"ESTUDIANTE"
,"sexo":"ESTUDIANTE","mensaje":""}
    
answered by 16.12.2016 в 16:43
0

Using SimpleXMLElement ref: link

$xml = new SimpleXMLElement($string);
$xml->registerXPathNamespace('ns2', 'http://__/');
$result = $xml->xpath('//ns2:getFichaGeneralResponse');
print_r($result);

Code taking question xml:

<?php
$string = '<?xml version="1.0"?> 
<Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:getFichaGeneralResponse xmlns:ns2="http://__/">
         <return>
            <codigoPaquete>198</codigoPaquete>
            <instituciones>
               <datosPrincipales>
                  <registros>
                     <campo>cedula</campo>
                     <codigo>1</codigo>
                     <valor>__</valor>
                  </registros>
                  <registros>
                     <campo>nombre</campo>
                     <codigo>2</codigo>
                     <valor>BUENAÑO RODRIGUEZ CARLOS DAVID</valor>
                  </registros>
                  <registros>
                     <campo>genero</campo>
                     <codigo>3</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>condicionCiudadano</campo>
                     <codigo>4</codigo>
                     <valor>CIUDADANO</valor>
                  </registros>
                  <registros>
                     <campo>fechaNacimiento</campo>
                     <codigo>5</codigo>
                     <valor>04/11/1986</valor>
                  </registros>
                  <registros>
                     <campo>lugarNacimiento</campo>
                     <codigo>6</codigo>
                     <valor>PICHINCHA/QUITO/SAN BLAS</valor>
                  </registros>
                  <registros>
                     <campo>nacionalidad</campo>
                     <codigo>7</codigo>
                     <valor>ECUATORIANA</valor>
                  </registros>
                  <registros>
                     <campo>estadoCivil</campo>
                     <codigo>8</codigo>
                     <valor>CASADO</valor>
                  </registros>
                  <registros>
                     <campo>conyuge</campo>
                     <codigo>10</codigo>
                     <valor>BOLAÑOS HERNANDEZ JESENIA LILIANA</valor>
                  </registros>
                  <registros>
                     <campo>domicilio</campo>
                     <codigo>15</codigo>
                     <valor>PICHINCHA/QUITO/CHAUPICRUZ</valor>
                  </registros>
                  <registros>
                     <campo>callesDomicilio</campo>
                     <codigo>16</codigo>
                     <valor>GRANDA CENTENDO SEBASTIAN CEDE</valor>
                  </registros>
                  <registros>
                     <campo>numeroCasa</campo>
                     <codigo>17</codigo>
                     <valor>OE5-130</valor>
                  </registros>
                  <registros>
                     <campo>fechaDefuncion</campo>
                     <codigo>20</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>fechaInscripcionDefuncion</campo>
                     <codigo>39</codigo>
                     <valor/>
                  </registros>
                  <registros>
                     <campo>instruccion</campo>
                     <codigo>558</codigo>
                     <valor>SUPERIOR</valor>
                  </registros>
                  <registros>
                     <campo>profesion</campo>
                     <codigo>563</codigo>
                     <valor>ESTUDIANTE</valor>
                  </registros>
                  <registros>
                     <campo>sexo</campo>
                     <codigo>1328</codigo>
                     <valor>HOMBRE</valor>
                  </registros>
               </datosPrincipales>
               <nombre>Registro Civil</nombre>
            </instituciones>
         </return>
      </ns2:getFichaGeneralResponse>
   </soap:Body>
</Envelope>';

$xml = new SimpleXMLElement($string);
$xml->registerXPathNamespace('ns2', 'http://__/');
$result = $xml->xpath('//ns2:getFichaGeneralResponse');
print_r($result);
var_dump($result);

?>
    
answered by 15.09.2017 в 06:31