我正在从 MySQL 数据库检索数据,并显示一个表,其中包括:
item_id
item_image
(空)item_title
item_isbn
(包含连字符)
到目前为止,我的代码是有效的,因为我能够检索数据并将其显示在一个简单的表格中。
到目前为止我的代码;
型号
class Items_model extends CI_Model {
public function itemList() {
$query = $this->db->query("SELECT * FROM item LIMIT 10");
return $query->result_array();
}
}
查看
<table>
<tr>
<td><strong>ID</strong></td>
<td><strong>Image</strong></td>
<td><strong>Title</strong></td>
<td><strong>ISBN</strong></td>
</tr>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo $item['item_id']; ?></td>
<td><?php echo $item['item_image']; ?></td>
<td><?php echo $item['item_title']; ?></td>
<td><?php echo $item['item_isbn']; ?></td>
</tr>
<?php endforeach; ?>
</table>
Controller
class Items extends CI_Controller {
public function index() {
$data['items'] = $this->items_model->itemList();
$this->load->view('item_view', $data);
}
}
我想使用该书的 ISBN,使用 Open Library Covers API 检索该书的封面并填充 html 表中的图像字段。
显然,通过使用以下 URL 模式可以实现这一点;
http://covers.openlibrary.org/b/isbn/0385472579-S.jpg
在我看来,我尝试了以下代码,但它不起作用;
<td><img src="<?php echo ('http://covers.openlibrary.org/b/isbn/'. stripslashes($item['item_isbn']) .'-S.jpg');?>"/></td>
理想情况下,如果我也无法使用开放库 API 检索图像,我想显示标准的“未找到图像”jpg,但我确信我可以自己解决这部分问题(希望如此! )。
任何建议将不胜感激,对于 Codeigniter 来说非常陌生。
最佳答案
假设您的数据库中存储了有效的 ISBN,请将您的 View 更改为以下内容:
<table>
<tr>
<td><strong>ID</strong></td>
<td><strong>Image</strong></td>
<td><strong>Title</strong></td>
<td><strong>ISBN</strong></td>
</tr>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo $item['item_id']; ?></td>
<td><img src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-S.jpg" /></td>
<td><?php echo $item['item_title']; ?></td>
<td><?php echo $item['item_isbn']; ?></td>
</tr>
<?php endforeach; ?>
</table>
如果未找到图像,则会显示 1px x 1px 透明像素。
因此显示图像的代码语法是:
<img src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-S.jpg" />
Resulting screenshot from my test
更新(如果未找到图像)
根据文档:
By default it returns a blank image if the cover cannot be found. If you append ?default=false to the end of the URL, then it returns a 404 instead.
要添加您自己的后备图像,您可以将此参数附加到图像 URL,然后检查该文件是否不存在。
有多种方法可以检查文件是否存在。使用curl可能是最优雅的,但这里是......
快速而肮脏的方法
这使用 ternary operator与 getimagesize 结合使用函数来处理后备。为此,您需要确保您的 PHP 版本启用了 GD(图像处理库)支持。
<img src="<?php echo (!getimagesize('http://covers.openlibrary.org/b/isbn/' . $item['item_isbn'] . '-S.jpg?default=false')) ? '/path/to/your-image.jpg' : 'http://covers.openlibrary.org/b/isbn/' . $item['item_isbn'] . '-S.jpg'; ?>" />
将三元运算符语法视为内联 if/else 语句。
关于php - Codeigniter 使用开放库 API 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42910204/