Reading and Replacing Text Using PhpPresentation - laravel

I want to access a Word from A pptx file in laravel using php presentations
I tried this but its not working.Kindly provide any input.
$slides = $oPHPPresentation2->getSlide(7);
$shape=$slides->getShapeCollection();
$paragraphs = $shape->getParagraphs();
foreach ($paragraphs as $paragraph_k => $paragraph_v)
{
$text_elements = $paragraph_v->getRichTextElements();
foreach ($text_elements as $text_element_k => $text_element_v)
{
$text = $text_element_v->getText();
$new_text = str_replace('[[recommendations]]','Pranjal', $text);
$text_element_v->setText($new_text);
}
}

Related

import phpexcel codeigniter except current cell value

i want to import from excel using php excel from my codeigniter with current cell containt current text
cell1
cell2
A
1
B
2
C
3
i want just cell except B in cell1 to insert database
my controller
public function import_excel(){
if (isset($_FILES["fileExcel"]["name"])) {
$path = $_FILES["fileExcel"]["tmp_name"];
$object = IOFactory::load($path);
foreach($object->getWorksheetIterator() as $worksheet)
{
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
for($row=2; $row<=$highestRow; $row++)
{
$cell1= $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$cell2= $worksheet->getCellByColumnAndRow(1, $row)->getValue();
$temp_data[] = array(
'cell1' => $cell1,
'cell2' => $cell2,
);
}
}
if($cell1 == 'B'){
}else{
$this->load->model('M_Admin');
$insert = $this->M_Admin->insert($temp_data);
}
but this failed and data still insert. please help me and many thanks you for help.
I never use phpexcel before, but if it's array and consider that $cell1 is a string/text, I guess you can try to use this:
for($row=2; $row<=$highestRow; $row++)
{
$cell1= $worksheet->getCellByColumnAndRow(0, $row)->getValue();
$cell2= $worksheet->getCellByColumnAndRow(1, $row)->getValue();
//cell value you want to hide
if ($cell1 == 'B') {
$cell1 = 'xxx'; //overwrite that value into something
}
$temp_data[] = array(
'cell1' => $cell1,
'cell2' => $cell2,
);
}
note: I'm using codeigniter 3

Customise the filename in phpword

Is it possible to customize the filename in phpword when I want to download it?
I want that the file takes the prenoms of the exported row.
My code:
public function edit (Stagiaire $stagiaire)
{
$id = $stagiaire ->id;
$desc1 = Stagiaire::find($id);
$my_template = new \PhpOffice\PhpWord\TemplateProcessor(public_path('templateStagiaire.docx'));
$my_template->setValue('id, $desc->id);
$my_template->setValue('prenoms, $desc->prenoms);
$my_template->setValue('nom, $desc->nom);
$filename = $stagiaire->prenoms;
try{
$my_template->saveAs(storage_path('templateStagiaire.docx'));
}catch (Réception $e){}
return response()->download(storage_path('".$filename.".docx));
}
Need help.
Thanks in advance.
Laravel example for downloading file:
public function edit(Stagiaire $stagiaire, $downloadName = null)
{
$id = $stagiaire->id;
$desc = Stagiaire::find($id);
$my_template = new \PhpOffice\PhpWord\TemplateProcessor(public_path('templateStagiaire.docx'));
$my_template->setValue('id', $desc->id);
$my_template->setValue('prenoms', $desc->prenoms);
$my_template->setValue('nom', $desc->nom);
// save as `prenoms` filename
$filename = $stagiaire->prenoms;
try {
$my_template->saveAs(storage_path("$filename.docx"));
} catch (Reception $e) {
}
// if download name is null, then use filename
$downloadName = $downloadName??$filename;
return response()->download(storage_path("$filename.docx"))
->header('Content-disposition','attachment; filename="'.$downloadName.'"');
}
Similar Laravel example

Google Cloud Speech to Text no output

Can't figure out why there is no output from this request. I loaded a 44100hz mp3 into this. It just outputs an empty object through dd(). I don't think its anything to do with the credentials. As iv enabled the API from the Google Cloud Console.
$speech = new SpeechClient([
'credentials' => storage_path("app/compute/google/cloud/service_accounts/keys/key1.json"),
]);
$file = file_get_contents($options["input_url"]);
// change these variables if necessary
$encoding = AudioEncoding::LINEAR16;
$sampleRateHertz = 44100;
$languageCode = 'en-US';
// get contents of a file into a string
// set string as audio content
$audio = (new RecognitionAudio())
->setContent($file);
// set config
$config = (new RecognitionConfig())
->setEncoding($encoding)
->setSampleRateHertz($sampleRateHertz)
->setLanguageCode($languageCode);
$response = $speech->recognize($config, $audio);
dd(($response->serializeToJsonString()));
foreach ($response->getResults() as $result) {
$alternatives = $result->getAlternatives();
$mostLikely = $alternatives[0];
$transcript = $mostLikely->getTranscript();
$confidence = $mostLikely->getConfidence();
$this->info('Transcript: %s' . PHP_EOL, $transcript);
$this->info('Confidence: %s' . PHP_EOL, $confidence);
}
}

Laravel help for optimize command script

I'm working with Lumen framework v5.8 (it's the same as Laravel)
I have a command for read a big XML (400Mo) and update datas in database from datas in this file, this is my code :
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->first();
if ($conditionId) {
ConditionTranslation::where(['condition_id' => $conditionId->id, 'locale' => 'fr'])->update(['name' => $name]);
$this->info(memory_get_usage());
}
}
}
}
}
So, I have to find in the XML each DescriptorUI element, the value corresponds to the mesh_id attribute of my class Condition.
So, with $conditionId = Condition::where('mesh_id', $meshId)->first(); I get the Condition object.
After that, I need to update a child of Condition => ConditionTranslation. So I just get the element DescriptorName and update the name field of ConditionTranslation
At the end of the script, you can see $this->info(memory_get_usage());, and when I run the command the value increases each time until the script runs very very slowly...and never ends.
How can I optimize this script ?
Thanks !
Edit : Is there a way with Laravel for preupdate multiple object, and save just one time at the end all objects ? Like the flush() method of Symfony
There is a solution with ON DUPLICATE KEY UPDATE
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
$keyValues = [];
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->value('id');
if ($conditionId) {
$keyValues[] = "($conditionId, '".str_replace("'","\'",$name)."')";
}
}
}
}
if (count($keyValues)) {
\DB::query('INSERT into `conditions` (id, name) VALUES '.implode(', ', $keyValues).' ON DUPLICATE KEY UPDATE name = VALUES(name)');
}
}

Generate MS word document in Joomla

What I try to accomplish:
Admin creates MS Word document with placeholders that will be filled with data from Joomla database
Admin uploades MS Word file to Joomla and connects it with SQL statement
User execute "Generate MS Word" function and gets MS Word document filled with data from database.
Is there any components for Joomla that does this?
I have done this in my application using Interop libraries.
recently I've done this for a joomla component using phpdocx and pclzip libraries, where
a *.docx file is generated from a template file.
Config:
$params = Object with form data; // data from requeest
$template = 'xml_file_name'; // jfrom xml file name and *.docx template file name
$pl = '#'; // place holder prefix & suffix: (example: #PLACEHOLDER#)
$date_placehold = '#DATE#'; // will be replaced with current date
$date_formt = 'F j, Y'; // php date format
$template_path = JPATH_COMPONENT_SITE .DS.'templates'.DS.$template.'.docx';
$temp_dir = JPATH_ROOT.DS.'tmp'.DS.'phpdocx-temp-dir'; // + write access
$output_mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$filename = $params->first_name .' - '. $params->second_name.'.docx';
// get names of all form fields of type 'list' from xml file
$lists = (array) ComponentHelper::getJFormLists($template);
// get all field names from the xml file
$fields = (array) ComponentHelper::getJFormFieldsNames($template);
Initialize variables:
$doc =& JFactory::getDocument();
$doc->setMimeEncoding($output_mime);
// require phpdocx class
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'pclzip.lib.php');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'phpdocx.php');
$phpdocx = new phpdocx($template_path, $temp_dir);
bind form fields with user params:
foreach($params as $field => $value)
{
if(array_key_exists($field,$lists) && is_array($lists[$field]) && array_key_exists($value, $lists[$field]) )
{
// if the field is JFormInput with type "list" its value is not important but its label
$var = $lists[$field][$value];
} else {
$var = $value;
}
// use openxml carriage return on new lines
if(strpos($var, "\n")) {
$var = str_replace("\n", '<w:br/>', $var);
}
$fields[$field] = $var;
}
foreach application form fields:
foreach($fields as $field => $value)
{
// replace placeholder with form value
$phpdocx->assign($pl.strtoupper($field).$pl, $value);
}
// assign date for filled-in applications
if(!empty($date_placehold)
{
$phpdocx->assign($date_placehold, date($date_formt));
}
output the file:
$phpdocx->stream($filename, $output_mime);
return true;

Resources