file_get_contents into a json variable- twitter module - php

I am extremely new to json and have been working on this issue for about a week.
I used php to retrieve tweets from a list of accounts and stored them into a .txt file
$cache = dirname(__FILE__) . '/../cache/twitter-json.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json? slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
$cachefile = fopen($cache, 'wb');
fwrite($cachefile,utf8_encode($data));
fclose($cachefile);
?>
The way the architect has the front-end page structured is that I need to store the json value (what I have in the .txt file) into a json variable in a .js file and render it.
edit:
so it has been changed to
$cache =_ _DIR__.'/cached.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json? slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
file_put_contents($cache, $data);
the file comes up empty. do you guys know what might be the problem?
Is it possible to store the contents of a .txt file into a json variable in a .js file?

No need to utf8_encode things as JSON is already UTF-8
You can simply use file_put_contents
file_put_contents($cache, 'var myvar = '.$data.';');
-edit-
Code to clarify my solution:
$cache = __DIR__.'/cached.txt';
$data = file_get_contents('http://api.twitter.com/1/lists/statuses.json?slug=widget&owner_screen_name=webcodepro&count=1&page=1&per_page=8&include_rts=true&include_entities=true');
file_put_contents($cache, 'var mydata = '.$data.';');

Is it possible to store the contents of a .txt file into a json variable in a .js file?
Yes, it is possible:
$txtFile = '/path/to/txt-file.txt';
$jsFile = '/path/to/js-file.js';
$jsPlate = "var jsVariable = %s;\n";
$string = file_get_contents($txtFile);
if (FALSE === $string) {
throw new RuntimeException('Failed to load text-file.');
}
$json = json_encode($string);
if (FALSE === $json) {
throw new RuntimeException('Failed to json encode string.');
}
$jsString = sprintf($jsPlate, $json);
$result = file_put_contents($jsFile, $jsString);
if (!$result) {
throw new RuntimeException('Failed to save javascript-file.');
}
Encoding Checklist:
The text-file is UTF-8 encoded.

Related

Automating CSV conversion from iso-8859-2 to utf-8

I have quite a few CSV files that are unfortunately encoded with iso-8859-2 (according to Brackets). I would like to iterate over these files with PHP and convert them.
I found https://csv.thephpleague.com/9.0/converter/charset/ but the way I can use the conversion function is uncertain to me.
Their example code
use League\Csv\CharsetConverter;
$csv = new SplFileObject('/path/to/french.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
$encoder = (new CharsetConverter())->inputEncoding('iso-8859-15');
$records = $encoder->convert($csv);
This is my code so far that is part of a form to upload one file and save the contents to the database for testing. It of course saves the text in the incorrect format.
$db = ConnectDB::getConnection('address_dtb');
$sql = " ... ";
$stmt = $db->prepare($sql);
$rowCount = 0;
$temp_name = $_FILES['adresscsv']['tmp_name'];
$file_handle = fopen($temp_name, 'r');
while (($items = fgetcsv($file_handle, 1000, ';')) !== FALSE) {
if($flag) { $flag = false; continue; }
$stmt->execute($items);
$rowCount++;
}
fclose($file_handle);
ConnectDB::closeConnection($db);
What is the correct way to use the PHP CSV library above to iterate over locally saved files in a for loop to automate the process?
I ended up using iconv as hinted.
$files = glob('address/*.csv');
foreach ($files as $csv) {
$file_data = file_get_contents($csv);
$utf8_file_data = iconv('Windows-1250', 'UTF-8', $file_data);
file_put_contents($csv, $utf8_file_data);
}
You do not have to use a library. There is a function in PHP that can do that iconv

PHP file stream data coming back in Binary

So I have a function that I CANNOT get to work. What's happening is it's coming back with data that's in binary and not the actual file. However, in the binary that I get back, the name of the particular file is included in the string. The data looks like this:
PK‹Mpt-BR/finalinport.html³)°S(ÉÈ,V¢‘ŒT…‚ü¢’ÒôÒÔâT…´Ì¼Ä ™” “I,QðT(ÏÌÉQ(-ÈÉOLQH„¨‡*Ê/B×]’X”žZ¢`£_`ÇPK.Ùô LePK‹M.Ùô Lept-BR/finalinport.htmlPKD
pt-BR is the directory and the 'finalinport.html' is the file that I am trying to have downloaded. If I replace the second parameter of fwrite to just a plain string, then everything works and I get the string that I wrote in a file inside of the zip. But not when I'm using Stream->getContents(), which leads me to believe that it is something going on with the stream. I cannot wrap my head around what can be happening. I've been on this for a week and a half now so any suggestions would be great.
public function downloadTranslations(Request $request, $id)
{
$target_locales = $request->input("target_locale");
$has_source = $request->input("source");
$client = new API(Auth::user()->access_token, ZKEnvHelper::env('API_URL', 'https://myaccount.com'));
$document = Document::find($id);
$job_document = JobDocument::where('document_id', $id)->first();
$job = Job::find($job_document->job_id);
$file = tempnam('tmp', 'zip');
$zip = new ZipArchive();
$zip->open($file, ZipArchive::OVERWRITE);
$name_and_extension = explode('.', $document->name);
if($target_locales == null){
$target_locales = [];
foreach ($job->target_languages as $target_language) {
$target_locales[] = $target_language['locale'];
}
}
foreach($target_locales as $target_locale){
$translation = $client->downloadDocument($document->document_id, $target_locale);
$filename = $name_and_extension[0] . ' (' . $target_locale . ').' . $name_and_extension[1];
if($translation->get('message') == 'true') {
//API brings back file in stream type
$stream = Stream::factory($translation->get('body'));
$newFile = tempnam(sys_get_temp_dir(), 'lingo');
$handle = fopen($newFile, 'w');
fwrite($handle, $stream->getContents());
$zip->addFile($newFile, 'eh.html');
fclose($handle);
}
else if($translation->get('message') == 'false'){
//API brings back file contents
$zip->addFromString($filename, $translation->get('body'));
}
}
$translation = $client->downloadDocument($document->document_id, null, null);
$filename = $name_and_extension[0]. ' (Source).'.$name_and_extension[1];
$zip->addFromString($filename, $translation->get('body'));
sleep(10);
$zip->close();
return response()->download($file, $name_and_extension[0].'.zip')->deleteFileAfterSend(true);
}
I'm unfamiliar with PHP streams and I don't have a debugger set up so I keep thinking it has something to do with how I am handling the stream. Because the other condition (the else if) is coming back as content of the file (string) and the if statement, the data is coming back as a stream resource, which I am unfamiliar with.
Stream::factory
is used in Guzzle 5, use json_encode for Guzzle 6.

Insert Mysql data into Json file doesn't work

I have a script that doesn't work I hope some developers of you know the solution.
<?php
//Create Database connection
$db = mysql_connect("localhost","d","d");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("d",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from events", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
$file = 'events.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
// Write the contents back to the file
file_put_contents($file, $json_response);
//Close the database connection
?>
But the events.json is empty? Does anyone know the solution?
first,
echo json_encode($json_response);
file_put_contents($file, $json_response);
this is not writing json you should do this
file_put_contents($file, json_encode($json_response));
maybe it's the issue, you can't write an array into a file.
second, are you missing some code ?
$current = file_get_contents($file);
// Append a new person to the file
we don't see the code to append here, your code just replaces the content by the array $json_response (and not a json encoded array).
You haven't stored the json encoded response anywhere. Below your echo statement, add the line:
$json_response = json_encode($json_response);
You write: // Append a new person to the file but never append, rather replaces the content of the file.
When you call file_put_contents($file, $json_response); you have not yet made $json_response into a json string.
Try change:
echo json_encode($json_response);
To:
$json_response = json_encode($json_response);
To correctly convert the data to a json-string.
To append the data to the file (now I'm going to assume that the file contains data formatted the same as the data you are trying to write), load it as you do with file_get_contents then convert the content to an associative array with: json_decode($dataFromFile, true); (the true flag as second argument makes the return value into an associative array, rather than an object) and merge the two lists, before writing it to file.
use this :
$json_response = json_encode($json_response);

PHP cache writes nothing to text file

I try to make my PHP cache with this code:
//Make cache files
$cache = 'tweets-cache.txt';
$date = 'tweets-date.txt';
$currentTime = time(); // Current time
// Get cache time
$datefile = fopen($date, 'r');
$cacheDate = fgets($datefile);
fclose($datefile);
//check if cache has expired
if (floor(abs(($currentTime-$cacheDate) / 10800)) <= $_GET['expiry'] && $cacheDate) {
$cachefile = fopen($cache, 'r');
$data = fgets($cachefile);
fclose($cachefile);
} else {
//Make the REST call
$data = (array) $cb->$api($params);
// update cache file
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, utf8_encode($data));
fclose($cachefile);
// update date file
$datefile = fopen($date, 'wb');
fwrite($datefile, utf8_encode(time()));
fclose($datefile);
}
//Output result in JSON, getting it ready for jQuery to process
echo json_encode($data);
Now he writes nothing in tweets-cache.txt.
i think it is because of he cannot write an array with utf8_encode.
Yes, you are right about utf8_encode() function. Try to write serialized data to the file:
fwrite($cachefile, json_encode($data));
and when you read your data back from the file, do de-serialization:
$data = json_decode(fgets($cachefile));
Also, you can make things simpler if you use functions like file_get/put_contents, so your code:
$cachefile = fopen($cache, 'r');
$data = fgets($cachefile);
fclose($cachefile);
will be:
$data = json_decode(file_get_contents($cache));
and:
// update cache file
$cachefile = fopen($cache, 'wb');
fwrite($cachefile, utf8_encode($data));
fclose($cachefile);
// update date file
$datefile = fopen($date, 'wb');
fwrite($datefile, utf8_encode(time()));
fclose($datefile);
translates to:
// update cache file
file_put_contents($cache, json_encode($data));
// update date file
file_put_contents($date, time());
Be aware of the synchronization problems you can face when you are using filesystem in multithreaded/multiprocess environment.
Two and more php instances can make attempt to write data to the same file in the same time, and you will get corrupted file.
You can use filesystem locking or special cache software like Memcached, which is much more preferable solution for such cases.
Memcached
PHP Reference: file_put_contents()
PHP Reference: file_get_contents()
PHP Reference: json_encode()

Manage several files in PHP

I'm testing php because I'm a freshman in this matter. I put my php code in a free server, they let me do my own index.php, manage some php variables (like register_globals, magic_quotes_gpc etc. I left them as default), but apparently I can handle not more than one file in a php code, for example:
<?php
//--------Updating Data-------------
$cdc = intval($_POST['cantidadDeCapitulos']);
$toWrite = array('ctot' => $cdc);
for($i=1;$i<$cdc+1;$i += 1){
$toWrite["cap".$i] = $_POST['numdeCap'.$i];
}//---------------------------------
$datos = file_get_contents("myfile.json.");
$toWrite = json_encode( $toWrite );
//Open a file in write mode
$fp = fopen("myfile2.json", "w");
if(fwrite($fp, "$toWrite")) {
echo "&verify=success&";
} else {
echo "&verify=fail&";
}
fclose($fp);
?>
If I comment out the line $datos = file_get_contents("myfile.json."); it's alright!, something is written in myfile2.json but if it is uncommented, the data is not updated. Both files have permission 666 and they are in the same directory i.e., /root.
$datos = file_get_contents("myfile.json.");
Seems like a typo has occurred. Take off the final dot from your file. I mean, change the line to:
$datos = file_get_contents("myfile.json");
try this:
<?php
$file = 'myfile.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Write the contents back to the file
file_put_contents($file, $current);
?>

Categories