php xml 保存到array数组

 更新时间:2016年11月25日 15:59  点击:1467

<?php

function xmlStringToArray($xmlString)
        {
        $xmlString = preg_replace('/<!--.*?-->/s','',$xmlString);
        $exitAfterManyLoops = 0;
        $xmlArray = array();
        $currentNode = &$xmlArray;
        $currentHierarchy = array();
        $currentDepth = 0;
        while($xmlString != '')
                {
                $exitAfterManyLoops++;
                if($exitAfterManyLoops > 300)
                        {
                        print "BREAK";
                        break;
                        }
                $xmlString = trim(substr($xmlString, strpos($xmlString, '<')));
                $thisNodeAscends = (substr($xmlString, 1, 1) == '/');
                $thisNodeDescends = (substr($xmlString, strpos($xmlString, '>') - 1, 1) != '/');
                $nodeName = substr($xmlString, 1, strpos($xmlString, ' ') -1);
                $openElement = substr($xmlString, strpos($xmlString, ' ') + 1);
                $openElement = substr($openElement, 0, strpos($openElement, '>') );
                if(substr($openElement, strlen($openElement) - 1, 1) == "/")
                        {
                        $openElement = substr($openElement, 0, strlen($openElement) - 1);
                        }

                if($thisNodeAscends)
                        {
                        $currentDepth--;
                        $currentNode = &$currentHierarchy[$currentDepth];
                        }
                else
                        {
                        if($thisNodeDescends)
                                {
                                $currentNode[] = array('__attributes' => parseXmlAttributesString($openElement), '__children' => array(), '__nodeName' => $nodeName);
                                $currentHierarchy[$currentDepth] = &$currentNode;
                                $currentDepth++;
                                $lastItem = &$currentNode[count($currentNode) - 1];
                                $currentNode = &$lastItem['__children'];
                                }
                        else //this node is at the same level
                                {
                                $currentNode[] = array('__attributes' => parseXmlAttributesString($openElement), '__nodeName' => $nodeName);
                                }

                        }
                $xmlString = substr($xmlString, strpos($xmlString, '>') + 1);
                }
        return $xmlArray;
        }

 

function parseXmlAttributesString($xmlElementString)
        {
        $exitAfter100Loops = 0;
        $xmlElementArray = array();
        while($xmlElementString != '')
                {
                $exitAfter100Loops++;
                if($exitAfter100Loops > 100)
                        {
                        print "BREAK";
                        break;
                        }
                $equalsCharacterPos = strpos($xmlElementString, '=');
                $key = trim(substr($xmlElementString, 0, $equalsCharacterPos));
                $xmlElementString = substr($xmlElementString, $equalsCharacterPos + 1);
                $openBracket = substr($xmlElementString, 0, 1);
                $xmlElementString = substr($xmlElementString, 1);
                $endBracketPos = strpos($xmlElementString, $openBracket);
                $value = substr($xmlElementString, 0, $endBracketPos);
                $xmlElementString = substr($xmlElementString, $endBracketPos + 1);
                if($key)
                        {
                        $xmlElementArray[$key]=$value;
                        }
                }
        return $xmlElementArray;
        }

?>

我在学习PHP的,当我尝试做在session_start() - 获取有关错误信息不能发送会话cookie。

我看到在这个问题上前面的问题,但是,仍然不能确定我的错误。

如果是错误家伙?
<?php
session_start();
      if ($_POST['add'])
      {
            foreach ($_POST['a_qty'] as $k => $v)
            {
                  $_SESSION['cart'][$k] = $_SESSION['cart'][$k] + $v;
            }
      }
?>
<?php
// look for catalog file
      $catalogfile = "catalog.dat";
      // file is avaialbe, extract data from it and place into $catalog, with sku as key
      if (file_exists($catalogfile))
      {
            $data = file($catalogfile);
            foreach ($data as $line)
            {
                  $lineArray = explode(":", $line);
                  $sku = trim($lineArray[0]);
                  $CATALOG[$sku]['desc'] = trim($lineArray[1]);
                  $CATALOG[$sku]['price'] = trim($lineArray[2]);                             
            }
      }
      else
      {
            die("Could not find the catalog file");
      }
?>
<table border="1" cellspacing="10">
<?php
            // print items from the catalog for selection
            foreach ($CATALOG as $k => $v)
            {
                  echo "<tr><td colspan=2 width=750>";
                  echo "<b>" . $v['desc'] . "</b>";
                  echo "</td></tr>";
                  echo "<tr><td>";
                  echo "Price per unit: " . $CATALOG[$k]['price'];
                  echo "</td><td>Quantity: ";
                  echo "<input size=4 type=text name="a_qty[" . $k . "]">";
                  echo "</td></tr> ";
            }
?>

<?php

function copyViaFtpRecursively($uploadLocation, $previewPath, $remoteDirectory, $ftpType)
        {
        $errorMessage = '';

        $connectionId = getFtpConnection($uploadLocation['host'], $uploadLocation['username'], $uploadLocation['password'], $uploadLocation['port']);
        switch($ftpType)
                {
                case 'active':
                        ftp_pasv($connectionId, False);
                        break;
                case 'passive':
                        ftp_pasv($connectionId, True);
                        break;
                }

        $baseDirectory = $uploadLocation['baseDirectory'];
        if(substr($baseDirectory, strlen($baseDirectory) - 1, 1) != '/')
                {
                $baseDirectory .= '/';
                }
        ftp_mkdir($connectionId, $baseDirectory); // No point showing an error message if the directory exists (most likely cause of error) because it will exist (at least) after the first time.

        $remoteBaseDirectory = $baseDirectory.$remoteDirectory;
        if(substr($remoteBaseDirectory, strlen($remoteBaseDirectory) - 1, 1) == '/')
                {
                $remoteBaseDirectory = substr($remoteBaseDirectory, 0, strlen($remoteBaseDirectory) - 1);
                }

        $remoteBaseDirectory .= '/';
        $errorMessage .= copyFileViaFtp($previewPath, $remoteBaseDirectory, $connectionId);

        ftp_close($connectionId);

        $errorHtml = '';
        if($errorMessage)
                {
                $errorHtml = nl2br($errorMessage);
                }
        return $errorHtml;
        }

function getFtpConnection($host, $username, $password, $port)
        {
        $connectionId = ftp_connect($host);
        if(!@ftp_login($connectionId, $username, $password))
                {
                webServiceError('FTP error. Unable to connect to "'.$host.'" with username "'.$username.'"');
                }
        return $connectionId;
        }


function copyFileViaFtp($sourcePath, $destinationPath, $connectionId)
        {
        $errorMessage = '';
        $sourcePath = str_replace(" ", "-", $sourcePath);
        $destinationPath = str_replace(" ", "-", $destinationPath);
        if(!ftp_mkdir($connectionId, $destinationPath))
                {
                $errorMessage .= "Unable to create directory at ".$destinationPath." (it may already exist) ";
                }
        ftp_site($connectionId, 'CHMOD 0777 '.$destinationPath);
        ftp_chdir($connectionId, $destinationPath);
        //print $sourcePath.' to '.$destinationPath."<br />";
        if(is_dir($sourcePath))
                {
                chdir($sourcePath);
                $handle=opendir('.');
                while(($file = readdir($handle))!==false)
                        {
                        if(($file != ".") && ($file != ".."))
                                {
                                if(is_dir($file))
                                        {
                                        $errorMessage .= copyFileViaFtp($sourcePath.DIRECTORY_SEPARATOR.$file, $file, $connectionId);
                                        chdir($sourcePath);
                                        if(!ftp_cdup($connectionId))
                                                {
                                                $errorMessage .= "Unable to ftp_cdup. ";
                                                }
                                        }
                                else
                                        {
                                        if(substr($file, strlen($file) - 4, 4) != ".zip")
                                                {
                                                $fp = fopen($file,"r");
                                                if(!ftp_fput($connectionId, str_replace(" ", "_", $file), $fp, FTP_BINARY))
                                                        {
                                                        $errorMessage .= "Unable to ftp_fput(). ";
                                                        }
                                                ftp_site($connectionId, 'CHMOD 0755 '.str_replace(" ", "_", $file));
                                                }
                                        }
                                }
                        }
                closedir($handle);
                }

        return $errorMessage;
        }

 代码如下 复制代码

function _link($url){
 $contents = @file_get_contents("$url");
 if($contents=="Forbidden" || $contents==""){
  $ch = curl_init();
  $timeout = 5;
  curl_setopt ($ch, CURLOPT_URL, "$url");
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  $contents = curl_exec($ch);
  curl_close($ch);
 }
 if(empty($contents)){
  exit('<font color=red>cant locaion.</font>');
 }
 preg_match_all("/charset=(.*?)>/is",$contents,$cod);
 if(!empty($cod[1][0])){
  if(preg_match("/utf-8/i",$cod[1][0])){
   $contents=iconv("UTF-8","gbk//TRANSLIT",$contents);
  }
 }
 return $contents;
}

 代码如下 复制代码

preg_match_all("/<a(.*?)href=(.*?)</a>/i",$webContent,$link);
 $urls =array();
 foreach($link[0] as $value)
 {
  if(strstr($value,'http') )
  {
   if(strstr($value, $ex[3]) || strstr( $value,$ex[0]) || strstr($value,$ex[1]) || strstr($value,$ex[2]))
   {
     continue;
   }
   else
   {
    preg_match_all("/hrefs*=s*(['"]?)(.*?)\1/is", $value, $vlink);    
    $urls[] = $vlink[2];
   }
  }
 }
 $strUrl = deleteEmptyArray( $urls);

function deleteEmptyArray( $val )
{
 $links ='';
 if( is_array( $val ) )
 {
  foreach( $val as $v =>$_v)
  {
   if( !empty( $_v[0] ) )
   {
    $links .=$_v[0].'|';
   }
  }  
  return substr($links,0,-1);
 }
 else
 {
  return false;
 }
}

 

[!--infotagslink--]

相关文章

  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • php中去除文字内容中所有html代码

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • php数组操作 键名比较 差集 交集赋值

    本文章提供在量的数据中级操作实例有如对键名比较计算数组的差集 计算差集 给指定数组中插入一个元素 反转数组 交集赋值新的数组实例。 //定义回调函数 funct...2016-11-25
  • C#二维数组基本用法实例

    这篇文章主要介绍了C#二维数组基本用法,以实例形式分析了C#中二维数组的定义、初始化、遍历及打印等用法,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php curl模拟post请求和提交多维数组的示例代码

    下面一段代码给大家介绍php curl模拟post请求的示例代码,具体代码如下: <&#63;php$uri = "http://www.cnblogs.com/test.php";//这里换成自己的服务器的地址// 参数数组$data = array ( 'name' => 'tanteng'// 'passwor...2015-11-24
  • C#数组的常用操作方法小结

    Array数组在C#中同样是最基本的数据结构,下面为大家C#数组的常用操作方法小结,皆为细小的代码段,欢迎收看收藏...2020-06-25
  • C#实现字符串转换成字节数组的简单实现方法

    这篇文章主要介绍了C#实现字符串转换成字节数组的简单实现方法,仅一行代码即可搞定,非常简单实用,需要的朋友可以参考下...2020-06-25
  • index.php怎么打开?如何打开index.php?

    index.php怎么打开?初学者可能不知道如何打开index.php,不会的同学可以参考一下本篇教程 打开编辑:右键->打开方式->经文本方式打开打开运行:首先你要有个支持运行PH...2017-07-06
  • C# 拷贝数组的几种方法(总结)

    下面小编就为大家带来一篇C# 拷贝数组的几种方法(总结)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • PHP 二维数组根据某个字段排序的具体实现

    本文记录的要实现的功能类似于 MySQL 中的 ORDER BY,上个项目中有遇到这样的一个需求。 要求:从两个不同的表中获取各自的4条数据,然后整合(array_merge)成一个数组,再根据数据的创建时间降序排序取前4条。 遇到这个...2014-06-07
  • c#将字节数组转成易读的字符串的实现

    这篇文章主要介绍了c#将字节数组转成易读的字符串的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C#读取文件所有行到数组的方法

    这篇文章主要介绍了C#读取文件所有行到数组的方法,涉及C#针对文件及数组的相关操作技巧,需要的朋友可以参考下...2020-06-25
  • PHP中func_get_args(),func_get_arg(),func_num_args()的区别

    复制代码 代码如下:<?php function jb51(){ print_r(func_get_args()); echo "<br>"; echo func_get_arg(1); echo "<br>"; echo func_num_args(); } jb51("www","j...2013-10-04
  • 将二维数组转为一维数组的2种方法

    如何将下面的二维数组转为一维数组。复制代码 代码如下:$msg = array(  array(    'id'=>'45',    'name'=>'jack'  ),  array(    'id'=>'34',    'name'=>'mary'  ),  array(    'id...2014-05-31
  • php中数组写入文件方法

    在php中为我们提供了一个函数var_export 他可以直接将php代码入到一个文件中哦。 代码如下 复制代码 var_export($times,true);后面不加tru...2016-11-25
  • PHP编程 SSO详细介绍及简单实例

    这篇文章主要介绍了PHP编程 SSO详细介绍及简单实例的相关资料,这里介绍了三种模式跨子域单点登陆、完全跨单点域登陆、站群共享身份认证,需要的朋友可以参考下...2017-01-25
  • PHP 如何获取二维数组中某个key的集合

    本文为代码分享,也是在工作中看到一些“大牛”的代码,做做分享。 具体是这样的,如下一个二维数组,是从库中读取出来的。 代码清单: 复制代码 代码如下: $user = array( 0 => array( 'id' => 1, 'name' => '张三', 'ema...2014-06-07
  • PHP实现创建以太坊钱包转账等功能

    这篇文章主要介绍了PHP实现创建以太坊钱包转账等功能,对以太坊感兴趣的同学,可以参考下...2021-04-20