I have found pdf to byte array and vice-versa in java,dotnet and python. But i want to convert pdf to byte array in php laravel. I am using "IMUIS" which is accounting software solution and need to sending journal entries from laravel lumen to "IMUIS" for processing.But it gives the error after converting.
"Foutmelding": "Kan een object van het type System.String niet converteren naar het type System.Byte[]."
In english that means
"Error message": "Can not convert a System.String object to the System.Byte [] type."
The documentation is given here:
doc link
Here is the code for it.
public function saveJournal($values = '') {
//echo "adasd";dd();
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$str = base64_encode($file);
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $str
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
and here is the response as well:
{
"success": true,
"result": {
"CreateJournaalpostResult": false,
"Journaalpost": "<?xml version=\"1.0\"?>\n<NewDataSet><BOE><JR>2018</JR><PN>5</PN><DAGB>20</DAGB><REK>20032</REK><TEGREK>40</TEGREK><FACT>0</FACT><BTW>4</BTW><BEDRBOEK>123.45</BEDRBOEK><DAT>08-05-2018</DAT><OPM>Anand testing from wsdl</OPM><BEDRBTW>21</BEDRBTW><OMSCHR>Testing from wsdl api</OMSCHR><BOEKSTUK>2018075</BOEKSTUK></BOE><DIGDOS><FILE>JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL1Jlc291cmNlcyAyIDAgUgovQ29udGVudHMgNCAwIFI+PgplbmRvYmoKNCAwIG9iago8PC9GaWx0ZXIgL0ZsYXRlRGVjb2RlIC9MZW5ndGggMzg2Pj4Kc3RyZWFtCniclZNPb9pAEMXvfIp3TA8Zdme93jE3G0xFJWgKJtdolbhICTYU6L9v3zWEGKnUVeST1++9+b2xzfjUU2QdfvayAv2xRkJKofiKvOh9g00ssUCFS0xMzFDNY0uxw2OF/kRjtMGXxms06QSOLUnwP+Fmkd+lyMr9wddP+9r7aoDxfFE8NOfaKqtZO+PoV7X+gOK5mdekSBhg/opJfb0qK+9fDthsB2Cl5VbZWx1D80DZAbtzhiIX2iiSJGBTIoLd6mo1hRXesGMRSuxx3ixNpxjl2aRY5vPX1NDwzcASk1GXjnE6LJbL+Ww5nV51RCykokvHZDZMF5+R5aN5+rF1BJ2xcDoiY1DBSmBT5/s1FqceDPl3D8fEpxmj8schLB/DTbX19e+OJq1Hc+Q6CrTCJBzwFeUrhQ1fTfROitYTs+mAaHVamU4KI8TmnRStJ+Zr0WeKVvefVbBu/prjS6/333e+fiwx9bVflbs9MrqnDpjWq7WRDpoLYSTOUXyxwD9RUucvCmVuZHN0cmVhbQplbmRvYmoKMSAwIG9iago8PC9UeXBlIC9QYWdlcwovS2lkcyBbMyAwIFIgXQovQ291bnQgMQovTWVkaWV5s7I11RFTyPO/t9OL74tl5/das6enN0bXwr//AKZ629kqeo76x9P/AOOs4y+N/wDK6nJuq/7nerWTI6zQrTReVjEVir+fVST/AF1m6Wrf7W+uMQ+o/D744dNdW2I8fKx2Ny8nCOrKu5j18zJOGq/JoeLX9ndp47YfR9t7+zUmmy59IPG9wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABuIAowMDAwMDc2NDgzIDAwMDAwIG4gCjAwMDAwNzY1NTkgMDAwMDAgbiAKdHJhaWxlcgo8PAovU2l6ZSAxMQovUm9vdCAxMCAwIFIKL0luZm8gOSAwIFIKPj4Kc3RhcnR4cmVmCjc2NjA5CiUlRU9GCg0KCiAgICAgIA==</FILE></DIGDOS></NewDataSet>\n",
"Primarykey": null,
"Foutmelding": "Kan een object van het type System.String niet converteren naar het type System.Byte[]."
}
}
To convert PDF to byte array you will have to read the document using file_get_contents() and then parse it by function unpack().
<?php
public function saveJournal($values = '') {
$partnerKey = $values->input('Partnerkey');
$omgevingscode = $values->input('Environmentcode');
$file = file_get_contents($values->file('Pdffile'));
$byte_array = unpack("C*",$file);
$base64_encode = base64_encode(serialize($byte_array));
$options = array(
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_URL => env('IMUIS_URL'),
\WsdlToPhp\PackageBase\AbstractSoapClientBase::WSDL_CLASSMAP => ClassMap::get(),
);
$login = new \mysdk\ImuisSDK\ServiceType\Login($options);
if ($login->Login(new \mysdk\ImuisSDK\StructType\Login($partnerKey, $omgevingscode)) !== false) {
$sessionid = $login->getResult()->SessionId;
}
$array = [
'BOE' => [
'JR' => '2018',
'PN' => '5',
'DAGB' => 20,
'REK' => 20032,
'TEGREK' => '40',
'FACT' => 0,
'BTW' => 4,
'BEDRBOEK' => 123.45,
'DAT' => '08-05-2018',
'OPM' => 'Anand testing from wsdl',
'BEDRBTW' => 21,
'FACT' => 0,
'OMSCHR' => 'Testing from wsdl api',
'BOEKSTUK' => 2018075
],
'DIGDOS' => [
'FILE' => $base64_encode
]
];
$journaalpost = ArrayToXml::convert($array, 'NewDataSet');//convert array to xml string
$create = new \mysdk\ImuisSDK\ServiceType\Create($options);
if ($create->CreateJournaalpost(new \mysdk\ImuisSDK\StructType\CreateJournaalpost($partnerKey, $omgevingscode, $sessionid, $journaalpost)) !== false) {
$jsonResponse = $create->getResult();
} else {
$jsonResponse = $create->getLastError();
}
return $jsonResponse;
}
?>
I think the problem is that WsdlToPhp has constructed client code which is sending the PDF entity as a String, when it needs to be a byte[].
So I think the problem may be in code that is not shown here.
Can you take a look at the code generated by WsdlToPhp and see if you have any flexibility in how the $journaalpost is serialized to see if you can fix in there?
// Convert the Base64 string back to text.
var byteString = atob(data.reportBase64Bytes);
// Convert that text into a byte array.
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// Blob for saving.
var blob = new Blob([ia], { type: "application/pdf" });
// Tell the browser to save as report.pdf.
saveAs(blob, "report.pdf");
// Alternatively, you could redirect to the blob to open it in the browser.
//document.location.href = window.URL.createObjectURL(blob);
There is a "bug" in the IMUIS software so it cant be possible to link a pdf file from php. Its may be done by Dotnet because its native language and the entire system built by it. Thanks to all of my SO friends for your efforts to helps me to find the issue, i have confirmed this information after call support. So in the future no one get stuck (afterall maybe end of 2018) :)
Related
Using this lib uploading works great. I have number of objects in an excel and I go through them and do whatever I desire.
The question is while uploading the excel I am ought to check whether a particular object already exists, if so increment the $rejected variable otherwise create and increment the $uploaded variable. As a result I would like to return the results: how many uploaded and how many rejected? Whats the best way to do as such? It is obvious I can't access those variables inside the function. What's the best practice here?
public function uploadUsingFile($file)
{
$rejected = 0;
$uploaded = 0;
Excel::load($file, function ($reader) {
foreach ($reader->toArray() as $row)
{
$plateAlreadyExist = Plate::where('serial_number', $row['plate_serial_number'])->exists();
if ($plateAlreadyExist) {
$rejected += 1;continue;
}
$supplier = Supplier::firstOrCreate(['name' => $row['supplier_name']]);
$statusName = EquipmentStatusCode::firstOrCreate(['name' => $row['status_name']]);
$plateType = PlateType::firstOrCreate(['name' => $row['plate_type_name']]);
$process = Process::firstOrCreate(['name' => $row['process_name']]);
$project = Project::firstOrCreate(['name' => $row['project_name']]);
$plateQuality = PlateQuality::firstOrCreate(['name' => $row['plate_quality']]);
$wafer = Wafer::firstOrCreate(['serial_number' => $row['wafer_serial_number']]);
$data = [
'serial_number' => $row['plate_serial_number'],
'crc_code' => $row['crc_code'],
'supplier_id' => $supplier['id'],
'equipment_status_code_id' => $statusName['id'],
'plate_type_id' => $plateType['id'],
'process_id' => $process['id'],
'project_id' => $project['id'],
'plate_quality_id' => $plateQuality['id'],
'wafer_id' => $wafer['id'],
'created_by' => Auth::user()->id,
];
if($data)
{
Plate::create($data);
$uploaded += 1;
}
}
});
return [ 'uploaded' => $uploaded, 'rejected' => $rejected ];
}
You can pass a reference to the variables into the closure by using the use keyword:
...
Excel::load($file, function ($reader) use(&$rejected, &$uploaded){
...
}
Anonymous Functions
I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1
I have a php file I am using to create a JSON output. You can see my loop in the code below:
foreach($objQueueData->event as $event){
$output[] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
array_push($output, $impactedRegions);
}
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
My issue is with the second array impactedRegions. This should be a sub array of output but it is not working as intended.
I am trying to have it be apart of the output array.
Here is what the current JSON output looks like:
[
{
"eventID": 25,
"eventTitle": "Monday",
"eventDescription": "Testing Monday",
"eventSource": "OE",
"eventType": "New Hire",
"eventMedium": "ILT",
"eventRequestor": "Carl",
"eventRequestorNTID": "ch123",
"eventRequestDate": "Nov 17 2014 4:58PM",
"eventDirector": "",
"eventTeammateImpact": "Medium",
"eventCustomerImpact": "High",
"eventComplexity": "Low",
"eventInitiativeID": 1069,
"eventNeededBy": "2014-11-18"
},
[
{
"0": "Americas"
}
],
Can anyone point me in the right direction?
foreach ($event->regionalImpact->option as $region) {
$output['regions'][] = $region->impact;
}
Try this
foreach($objQueueData->event as $key => $event){
$output[$key] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
}
$output[$key]['impactedRegions'] = $impactedRegions;
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
I think the problem you are having is you are using array_push() with an associative array. I believe array_push is for pushing values to an indexed array.
Trying specifying the key by using $output['impactedRegions'] = $impactedRegions; instead.
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
$output['impactedRegions'] = json_encode($impactedRegions);
}
Also, json_encode($impactedRegions) will encode the array so it's included as a json object in your original array.
First, im new in PHP so please bear with me.
Im creating a web service for android, and this is my code :
if($size > 0)
{
$resultArray = array();
foreach($result as $child)
{
if($child)
{
//add to array
$resultArray[] = array('result' => 'true',
'total' => $size,
'id' => $child['id'],
'user_id' => $child['user_id'],
'name' => $child['name'],
'gender' => $child['gender'],
'born_date' => $child['born_date'],
'born_hour' => $child['born_hour'],
'hospital' => $child['hospital']);
}
}
$this->response($resultArray, 200);
}
else
{
$this->response(array('result' => 'false'), 404);
}
I use the size to validate whether the result is OK 200 (has some data) or error 404. However, there is a possibility that the result's size is 0 (no data) but the result is OK (code 200). How to tell the different?
I tried to use boolean variable instead of $size, but its not working.
Thanks for your help.
I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning