| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 视频教程 | 素材下载 | 程序代码下载 | JS代码 | 论坛 | 
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
利用AJAX进行PHP开发
作者:佚名    文章来源:网络    点击数:    更新时间:2006-11-7
 



 扩展相册

  使用 Sajax 把我们的相册变成活动的 Web 应用程序如此轻而易举,我们要再花点时间添加一些功能,进一步说明 Sajax 如何使从服务器检索数据变得完全透明。我们将为相册添加元数据功能,这样用户就能为他们的图片添加说明。

  元数据

  没有上下文说明的相册是不完整的,比如照片的来源、作者等。为此我们要将图像集中起来创建一个简单的 XML 文件。根节点是 gallery,它包含任意多个 photo 节点。每个 photo 节点都通过其 file 属性来编号。在 photo 节点中可以使用任意多个标记来描述照片,但本例中只使用了 date、locale 和 comment。

  清单 12. 包含元数据的 XML 文件

<?xml version="1.0"?>
<gallery>
 <photo file="image01.jpg">
  <date>August 6, 2006</date>
  <locale>Los Angeles, CA</locale>
  <comment>Here's a photo of my favorite celebrity</comment>
 </photo>
 <photo file="image02.jpg">
  <date>August 7, 2006</date>
  <locale>San Francisco, CA</locale>
  <comment>In SF, we got to ride the street cars</comment>
 </photo>
 <photo file="image03.jpg">
  <date>August 8, 2006</date>
  <locale>Portland, OR</locale>
  <comment>Time to end our road trip!</comment>
 </photo>
</gallery>

  文件的解析不在本文讨论范围之列。我们假设您能够熟练使用 PHP 中众多 XML 解析方法中的一种。如果不熟悉的话,建议阅读 参考资料 中的文章。我们不再浪费时间解释如何将该文件转化成 HTML,作为一个练习,读者可以自己了解下面的代码如何使用 XML 文件并生成 HTML。清单 13 中的代码使用了 PHP V5 中自带的 SimpleXML 包。

  清单 13. 元数据函数

function get_meta_data ( $file ) {

 // Using getimagesize, the server calculates the dimensions
 list($width, $height) = @getimagesize("images/$file");
 $output = "<p>Width: {$width}px, Height: {$height}px</p>";

 // Use SimpleXML package in PHP_v5:
 // http://us3.php.net/manual/en/ref.simplexml.php
 $xml = simplexml_load_file("gallery.xml");

 foreach ( $xml as $photo ) {
  if ($photo['id'] == $file) {
   $output .= !empty($photo->date) ? "<p>Date taken:{$photo->date}</p>" : '';
   $output .= !empty($photo->locale) ? "<p>Location:{$photo->locale}>/p>" : '';
   $output .= !empty($photo->comment) ? "<p>Comment:{$photo->comment}</p>" : '';
  }
 }
 return $output;

  要注意的是,get_meta_data() 函数中还使用 getimagesize()(一个核心 PHP 函数,不需要 GD)计算图像的大小。

  再回到 get_image() 函数,它包含由 get_image_list() 生成的文件名的列表。查找元数据只需要将文件名传递给该函数即可。

  清单 14. 添加元数据

function get_image ( $index ) {
 $images = get_image_list ( 'images' );

 // ...

 $output .= '<img src="images/' . $images[$index] . '" />';
 $output .= '<div id="meta_data">' .
 get_meta_data( $images[$index] ) . '</div>';
 return $output;
}

  重新打开页面将看到服务器请求的结果。图 7 显示了带有元数据的放大的图像。

使用元数据的相册 
图 7. 使用元数据的相册
相关文章