Write and read the contents of a PHP file
Write file
file_put_contents(“file location”,“contents to write”); file_put_contents has a return value so it can be checked with an if statement
<?php
$check = file_put_contents("news_data/php_lesson.text","2020-08-28, writing file");
if ($check){
print ("write complete");
}else{
print ("write error");
}
?>
Read file
The return value of file_fet_contents becomes the read data
<?php
$check = file_get_contents("news_data/news.text");
print ($check);
?>
With read_file, you can print the return value without printing In this case, the read data cannot be processed
<?php
readfile("news_data/news.text");
?>
Add data
.= will be added after the string
<?php
$news = file_get_contents("news_data/news.text");
$news .= "Additional data";
file_put_contents("news_data/news.text",$news);
print ($news)
?>
If you want to add before the string
<?php
$news = file_get_contents("news_data/news.text");
$news = "Additional data". $news;
file_put_contents("news_data/news.text",$news);
print ($news)
?>
Read XML information
What is XML
XML is a type of markup language for describing the appearance and structure of text. Available in various fields that can be expanded. Generally used for RSS (update information).
<?php
$xmlTree = simplexml_load_file('http://nakata.net/feed/');
foreach ($xmlTree->channel->item as $item):
?>
・<a href="<?php print($item->link); ?>"><?php print($item->title); ?></a>
<?php
endforeach;
?>
The relationship of properties is like this,
-
access the elements inside item is an array so store it as $item
<channel>
<item>
<title></title>
<link></link>
</item>
</channel>
##JSON
JSON is an abbreviation for JavaScript Object Notation, which is a text-based data format similar to XML. Since it is short and easy to understand, it is used not only in JavaScript.
json content is after get_contents It can be converted into a PHP object by decoding Structure is different in xml and json
<?php
$file = file_get_contents('https://h2o-space.com/feed/json/');
$json =json_decode($file);
foreach ($json-> items as $item):
?>
・<a href="<?php print($item->url); ?>"><?php print($item->title); ?></a>
<?php
endforeach;
?>