찾다
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怎么除以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 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 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

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

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

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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음