搜索
首页php教程PHP源码XML与数据格式进行转换类

[PHP]代码 

<?php
/**
 * xml2array() will convert the given XML text to an array in the XML structure. 
 * Link: http://www.php.cn/ 
 * Arguments : $contents - The XML text 
 * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
 * $priority - Can be &#39;tag&#39; or &#39;attribute&#39;. This will change the way the resulting array sturcture. For &#39;tag&#39;, the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
 * Examples: $array =  xml2array(file_get_contents(&#39;feed.xml&#39;)); 
 * $array =  xml2array(file_get_contents(&#39;feed.xml&#39;, 1, &#39;attribute&#39;));
 */
function xml2array($contents, $get_attributes = 1, $priority = &#39;tag&#39;) {
    if (!$contents) return array();

    if (!function_exists(&#39;xml_parser_create&#39;)) {
        // print "&#39;xml_parser_create()&#39; function not found!";
        return array();
    } 
    // Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create(&#39;&#39;);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://www.php.cn/ 
    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, trim($contents), $xml_values);
    xml_parser_free($parser);

    if (!$xml_values) return; //Hmm...  
    // Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference  
    // Go through the tags.
    $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array 
    foreach($xml_values as $data) {
        unset($attributes, $value); //Remove existing values, or there will be trouble  
        // This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data); //We could use the array by itself, but this cooler. 
        $result = array();
        $attributes_data = array();

        if (isset($value)) {
            if ($priority == &#39;tag&#39;) $result = $value;
            else $result[&#39;value&#39;] = $value; //Put the value in a assoc array if we are in the &#39;Attribute&#39; mode 
        } 
        // Set the attributes too.
        if (isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if ($priority == &#39;tag&#39;) $attributes_data[$attr] = $val;
                else $result[&#39;attr&#39;][$attr] = $val; //Set all the attributes in a array called &#39;attr&#39; 
            } 
        } 
        // See tag status and do the needed.
        if ($type == "open") { // The starting of the tag &#39;<tag>&#39;
            $parent[$level-1] = &$current;
            if (!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
                $current[$tag] = $result;
                if ($attributes_data) $current[$tag . &#39;_attr&#39;] = $attributes_data;
                $repeated_tag_index[$tag . &#39;_&#39; . $level] = 1;

                $current = &$current[$tag];
            } else { // There was another element with the same tag name
                if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag . &#39;_&#39; . $level]] = $result;
                    $repeated_tag_index[$tag . &#39;_&#39; . $level]++;
                } else { // This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array 
                    $repeated_tag_index[$tag . &#39;_&#39; . $level] = 2;

                    if (isset($current[$tag . &#39;_attr&#39;])) { // The attribute of the last(0th) tag must be moved as well
                        $current[$tag][&#39;0_attr&#39;] = $current[$tag . &#39;_attr&#39;];
                        unset($current[$tag . &#39;_attr&#39;]);
                    } 
                } 
                $last_item_index = $repeated_tag_index[$tag . &#39;_&#39; . $level]-1;
                $current = &$current[$tag][$last_item_index];
            } 
        } elseif ($type == "complete") { // Tags that ends in 1 line &#39;<tag />&#39;
            // See if the key is already taken.
            if (!isset($current[$tag])) { // New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag . &#39;_&#39; . $level] = 1;
                if ($priority == &#39;tag&#39; and $attributes_data) $current[$tag . &#39;_attr&#39;] = $attributes_data;
            } else { // If taken, put all things inside a list(array)
                if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
                    // ...push the new element into that array.
                    $current[$tag][$repeated_tag_index[$tag . &#39;_&#39; . $level]] = $result;

                    if ($priority == &#39;tag&#39; and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag . &#39;_&#39; . $level] . &#39;_attr&#39;] = $attributes_data;
                    } 
                    $repeated_tag_index[$tag . &#39;_&#39; . $level]++;
                } else { // If it is not an array...
                    $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value 
                    $repeated_tag_index[$tag . &#39;_&#39; . $level] = 1;
                    if ($priority == &#39;tag&#39; and $get_attributes) {
                        if (isset($current[$tag . &#39;_attr&#39;])) { // The attribute of the last(0th) tag must be moved as well
                            $current[$tag][&#39;0_attr&#39;] = $current[$tag . &#39;_attr&#39;];
                            unset($current[$tag . &#39;_attr&#39;]);
                        } 

                        if ($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . &#39;_&#39; . $level] . &#39;_attr&#39;] = $attributes_data;
                        } 
                    } 
                    $repeated_tag_index[$tag . &#39;_&#39; . $level]++; //0 and 1 index is already taken 
                } 
            } 
        } elseif ($type == &#39;close&#39;) { // End of tag &#39;</tag>&#39;
            $current = &$parent[$level-1];
        } 
    } 

    return($xml_array);
} 

// Array to XML
class array2xml {
    public $output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    public $sub_item = array();
    public function __construct($array) {
        $sub_item = array();
        $this->output .= $this->xmlmake($array);
    } 
    public function xmlmake($array, $fk = &#39;&#39;) {
        $xml = &#39;&#39;;
        global $sub_item;
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $this->sub_item=array_merge($this->sub_item,array($fk));
                    $xml .= "<{$fk}>" . $this->xmlmake($value, $key) . "</{$fk}>";
                } else {
                    $xml .= "<{$key}>" . $this->xmlmake($value, $key) . "</{$key}>";
                } 
            } else {
                $xml .= "<{$key}>{$value}</{$key}>\n";
            } 
        } 
        return $xml;
    } 
    public function output(){
        foreach($this->sub_item as $t){
            $this->output = str_replace("<{$t}><{$t}>","<{$t}>",$this->output);
            $this->output = str_replace("</{$t}></{$t}>","</{$t}>",$this->output);
        }
        return $this->output;
    }
}

                   

                   

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境