Les saluda su queridísimo nekito incubo favorito 😸, ¡y hoy les traigo un tip súper útil! Como saben, soy de México, y me he encontrado con un reto técnico que tal vez muchos de ustedes también hayan enfrentado: la limpieza de archivos XML. En este país, los XML son bastante comunes, especialmente en temas de facturación y trámites, pero trabajar con ellos a veces puede ser un dolor de cabeza, ya que suelen venir llenos de caracteres extraños o desordenados que dificultan su lectura.
Este pequeño código procesa una respuesta en formato XML, extrayendo la información que necesitamos, ya sea desde un archivo o directamente desde la base de datos, y lo limpia para su posterior uso, utilizando el lenguaje de PHP . En este caso, el contenido en XML que queremos manejar se encuentra en una sección específica marcada por las etiquetas <s0:xml> ... </s0:xml>. El objetivo es lograr que el XML quede en un formato limpio y estructurado, lo que nos facilita mucho el trabajo de interpretación. Ahora, te explico cada parte para que puedas implementarlo fácilmente.
$stm = trim(htmlspecialchars_decode(html_entity_decode($xml->response)), " \t\n\r\"");
html_entity_decode($xml->response) : Decodifica cualquier entidad HTML en xml->response (por ejemplo, convierte & en &).htmlspecialchars_decode(...) : Elimina cualquier codificación de caracteres especiales HTML (por ejemplo, convierte " en ").trim(..., " \t\n\r\"") : Elimina espacios en blanco, tabulaciones, saltos de línea, retornos de carro y comillas (") del principio y final de la cadena resultante.El resultado es que $stm contiene el texto XML decodificado y limpiado de espacios y comillas externas.
$str_fin = strlen($stm);
Aquí simplemente se obtiene la longitud de la cadena $stm y se guarda en $str_fin, para usarla luego en la extracción.
<s0:xml>$str_inicio = strpos($stm, '<s0:xml>') + 8;strpos($stm, '<s0:xml>'): Encuentra la posición donde aparece la etiqueta <s0:xml> en $stm.+ 8: Suma 8 al índice encontrado para saltar la etiqueta completa (<s0:xml>), de modo que el índice de $str_inicio apunte justo después de la etiqueta de apertura.$str_tmp = substr($stm, $str_inicio, $str_fin);substr($stm, $str_inicio, $str_fin): Extrae una subcadena de $stm comenzando en $str_inicio y extendiéndose hasta $str_fin (longitud completa de $stm).$str_fin = strpos($str_tmp, '</s0:xml>');strpos($str_tmp, '</s0:xml>'): Encuentra la posición de la etiqueta de cierre </s0:xml> dentro de $str_tmp, indicando el final de la porción XML que nos interesa.$str_tmp = substr($str_tmp, 0, $str_fin);substr($str_tmp, 0, $str_fin): Extrae la subcadena desde el inicio de $str_tmp hasta la posición de cierre </s0:xml>, guardando solo el contenido XML deseado en $str_tmp.$str_tmp = preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp);preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp): Elimina todos los saltos de línea (\r y \n) de $str_tmp, dejándolo en una sola línea sin saltos.codigo completo
$stm = trim(htmlspecialchars_decode(html_entity_decode($xml->response))," \t\n\r"");
$str_fin = strlen($stm);
$str_inicio = strpos($stm, '<s0:xml>') + 8;
$str_tmp = substr($stm,$str_inicio,$str_fin);
$str_fin = strpos($str_tmp, '</s0:xml>');
$str_tmp = substr($str_tmp,0,$str_fin);
$str_tmp = preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp);
Con este proceso, logramos tomar solo la información relevante, limpiar esos molestos caracteres, y dejar el XML listo para usar en nuestras aplicaciones. Además, algo que me encanta de esta solución es su flexibilidad, porque podrías adaptarlo para otras etiquetas o incluso para datos similares que necesites en otros proyectos.
Con esta técnica espero que puedan encontrar una solución práctica para limpiar sus archivos XML o, al menos, que les sirva como guía para resolver problemas similares que encuentren en sus proyectos. ¡La idea es facilitarles el trabajo y que puedan interpretar sus datos sin estrés!
Así que ya saben, si en algún momento se encuentran con un archivo XML desordenado o con caracteres extraños, ¡prueben este método y me cuentan cómo les va! Nos vemos en la próxima, y recuerden que estoy aquí para ayudarles en sus aventuras tecnológicas. 😸
Greetings from your beloved favorite incubator 😸, and today I bring you a super useful tip! As you know, I'm from Mexico, and I've encountered a technical challenge that perhaps many of you have also faced: cleaning XML files. In this country, XMLs are quite common, especially in billing and paperwork issues, but working with them can sometimes be a headache, since they usually come full of strange or disordered characters that make them difficult to read.
This little code processes a response in XML format, extracting the information we need, either from a file or directly from the database, and cleans it for later use, using the PHP language. In this case, the XML content we want to handle is located in a specific section marked by the tags <s0:xml> ... </s0:xml>. The goal is to get the XML into a clean and structured format, which makes it much easier for us to interpret it. Now, I'll explain each part so you can easily implement it.
$stm = trim(htmlspecialchars_decode(html_entity_decode($xml->response)), " \t\n\r\"");
html_entity_decode($xml->response) : Decodes any HTML entity in xml->response (e.g. converts & to &).htmlspecialchars_decode(...) : Removes any HTML special character encoding (e.g. converts " to ").trim(..., " \t\n\r\"") : Removes whitespace, tabs, line breaks, carriage returns and quotes (") from the beginning and end of the resulting string.The result is that $stm contains the decoded XML text cleaned of spaces and external quotes.
$str_fin = strlen($stm);
Here we simply obtain the length of the string $stm and save it in $str_fin, to be used later in the extraction.
<s0:xml> tag$str_start = strpos($stm, '<s0:xml>') + 8;strpos($stm, '<s0:xml>'): Finds the position where the <s0:xml> tag appears in $stm.+ 8: Adds 8 to the index found to skip the entire tag (<s0:xml>), so that the index of $str_start points right after the opening tag.$str_tmp = substr($stm, $str_start, $str_end);substr($stm, $str_start, $str_end): Extracts a substring from $stm starting at $str_start and extending to $str_end (full length of $stm).$str_fin = strpos($str_tmp, '</s0:xml>');strpos($str_tmp, '</s0:xml>'): Finds the position of the closing tag </s0:xml> within $str_tmp, indicating the end of the XML portion we are interested in.$str_tmp = substr($str_tmp, 0, $str_fin);substr($str_tmp, 0, $str_fin): Extracts the substring from the start of $str_tmp to the closing position </s0:xml>, saving only the desired XML content in $str_tmp.$str_tmp = preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp);preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp): Removes all line breaks (\r and \n) from $str_tmp, leaving it on a single line without any breaks.full code
$stm = trim(htmlspecialchars_decode(html_entity_decode($xml->response))," \t\n\r"");
$str_fin = strlen($stm);
$str_inicio = strpos($stm, '<s0:xml>') + 8;
$str_tmp = substr($stm,$str_inicio,$str_fin);
$str_fin = strpos($str_tmp, '</s0:xml>');
$str_tmp = substr($str_tmp,0,$str_fin);
$str_tmp = preg_replace("/[\r\n|\n|\r]+/", "", $str_tmp);
With this process, we manage to take only the relevant information, clean those annoying characters, and leave the XML ready to use in our applications. Also, something I love about this solution is its flexibility, because you could adapt it for other tags or even for similar data that you need in other projects.
With this technique I hope you can find a practical solution to clean up your XML files or, at least, that it serves as a guide to solve similar problems you encounter in your projects. The idea is to make your work easier and that you can interpret your data without stress!
So you know, if at any time you find yourself with a messy XML file or with strange characters, try this method and tell me how it goes! See you next time, and remember that I am here to help you in your technological adventures. 😸
Portada realizada en photoshop
Separador realizado por @softy1231 softy1231
Vtuber, Paneles realizado por @panna-natha pannanatha
Logo realizado por KivaVT
Porta base realizada por @smile27