首页 > 开发 > PHP > 正文

必须收藏的php实用代码片段

2024-05-04 22:32:33
字体:
来源:转载
供稿:网友

在编写代码的时候有个神奇的工具总是好的!下面这里收集了 40+ PHP 代码片段,可以帮助你开发PHP 项目。 之前已经为大家分享了《必须收藏的23个php实用代码片段》。
这些PHP 片段对于PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧~

24. 从 PHP 数据创建 CSV 文件

function generateCsv($data, $delimiter = ',', $enclosure = '"') {  $handle = fopen('php://temp', 'r+');  foreach ($data as $line) {      fputcsv($handle, $line, $delimiter, $enclosure);  }  rewind($handle);  while (!feof($handle)) {      $contents .= fread($handle, 8192);  }  fclose($handle);  return $contents;}  

语法:

<?php$data[0] = "apple";$data[1] = "oranges";generateCsv($data, $delimiter = ',', $enclosure = '"');?>

25. 解析 XML 数据

$xml_string="<?xml version='1.0'?><moleculedb>  <molecule name='Benzine'>    <symbol>ben</symbol>    <code>A</code>  </molecule>  <molecule name='Water'>    <symbol>h2o</symbol>    <code>K</code>  </molecule></moleculedb>";   //load the xml string using simplexml function$xml = simplexml_load_string($xml_string);   //loop through the each node of moleculeforeach ($xml->molecule as $record){  //attribute are accessted by  echo $record['name'], ' ';  //node are accessted by -> operator  echo $record->symbol, ' ';  echo $record->code, '';}

26. 解析 JSON 数据

$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';$obj=json_decode($json_string);//print the parsed dataecho $obj->name; //displays rolfecho $obj->office[0]; //displays google

27. 获取当前页面 URL
这个 PHP 片段可以帮助你让用户登录后直接跳转到之前浏览的页面

function current_url(){$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];$validURL = str_replace("&", "&", $url);return validURL;}

语法:

<?phpecho "Currently you are on: ".current_url();?>

28. 从任意的 Twitter 账号获取最新的 Tweet

function my_twitter($username){   $no_of_tweets = 1;   $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $no_of_tweets;   $xml = simplexml_load_file($feed);  foreach($xml->children() as $child) {    foreach ($child as $value) {      if($value->getName() == "link") $link = $value['href'];      if($value->getName() == "content") {        $content = $value . "";    echo '<p class="twit">'.$content.' <a class="twt" href="'.$link.'" title=""> </a></p>';      }      }  }  }              
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表