在我的网站上,我展示了一些品牌和型号的产品。该数据通过PHP保存在网页上。 例如:
<?php
$producttype1 = array("01" => array("id"=>"01", "brand" => "ABC", "model" => "Hello"),
"02" => array("id"=>"02", "brand" => "ABC", "model" => "Hello"),
"03" => array("id"=>"03", "brand" => "ABC", "model" => "Hello"),
"04" => array("id"=>"04", "brand" => "ABC", "model" => "Hello"),
"05" => array("id"=>"05", "brand" => "ABC", "model" => "Hello"));
?>
这些产品由以下代码显示:
<?php foreach($producttype1 as $z)
{
?>
<a href="productdetail.php?type=producttype1&id=<?php echo $z["id"]; ?>&brand=<?php echo $z["brand"]; ?>&model=<?php echo $z["brand"]; ?>">
<div class="product_box">
<h3><?php echo $z["brand"]; ?></h3>
<div class="image_box">
<img src="images/producttype1/<?php echo $z["id"]; ?>.jpg" alt="" />
</div>
<p><?php echo $z["brand"]; echo " "; echo $z["model"]; ?></p>
</div></a>
<?php
}
?>
我想通过名为products.txt的文件访问此数据,因此数据不会保存在网页上。 我有办法吗?
答案 0 :(得分:0)
尝试:
$fp = fopen("products.txt", "w");
fwrite($fp, print_r($producttype1, true));
这会将products数组写入文本文件。
答案 1 :(得分:0)
$toBeWritten = $producttype1;
$fp = fopen("location/of/the/file/to/write.txt","a"); //replace file path as appropriate
fwrite($fp, serialize($toBeWritten)); // Serialization is easiest
fclose($fp);
请注意,序列化可以反转,阵列可以再次使用。
注意:不要使用相同的文件来存储多个数组/对象/等。因为他们会变得腐败。
要unserialize
再次使用:
$fileContents = '';
$fp = fopen("location/of/the/file/to/write.txt", "r");
$while !(feof($fp)) {
$fileContents .= fread($fp, 1024);
}
fclose($fp);
$productstype1 = unserialize($fileContents);