//load the xml string using simplexml $xml = simplexml_load_string($xml_string);
//loop through the each node of user foreach ($xml->user as $user) { //access attribute echo$user['id'], ' '; //subnodes are accessed by -> operator echo$user->name, ' '; echo$user->email, ' '; }
/****************** *@email - Email address to show gravatar for *@size - size of gravatar *@default - URL of default gravatar to use *@rating - rating of Gravatar(G, PG, R, X) */ functionshow_gravatar($email, $size, $default, $rating) { echo'<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email). '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" height="'.$size.'px" />'; }
15. PHP在字符断点处截断文字
所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Original PHP code by Chirp Internet: www.chirp.com.au // Please acknowledge use of this code by including this header. function myTruncate($string, $limit, $break=".", $pad="...") { // return with no change if stringis shorter than $limit if(strlen($string) <= $limit) return$string;
/* creates a compressed zip file */ functioncreate_zip($files = array(),$destination = '',$overwrite = false) { //if the zip file already exists and overwrite is false, return false if(file_exists($destination) && !$overwrite) { returnfalse; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreach($filesas$file) { //make sure the file exists if(file_exists($file)) { $valid_files[] = $file; } } } //if we have good files... if(count($valid_files)) { //create the archive $zip = newZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { returnfalse; } //add the files foreach($valid_filesas$file) { $zip->addFile($file,$file); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done! $zip->close();
//check to make sure the file exists returnfile_exists($destination); } else { returnfalse; } } /***** Example Usage ***/ $files=array('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true);
17. PHP解压缩 Zip 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/********************** *@file - path to zip file *@destination - destination directory for unzipped files */ functionunzip_file($file, $destination){ // create object $zip = newZipArchive() ; // open archive if ($zip->open($file) !== TRUE) { die (’Could not open archive’); } // extract contents to destination directory $zip->extractTo($destination); // close archive $zip->close(); echo'Archive extracted to directory'; }
18. PHP为 URL 地址预设 http 字符串
有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。
1 2 3 4
if (!preg_match("/^(http|ftp):/", $_POST['url'])) { $_POST['url'] = 'http://'.$_POST['url']; }