Encode Images at URL in PHP Array as Base64 - php

This is the code I have and I am trying to get and encode the image contents as base64 but I keep ending up with the URL as a base64 string.
In the end I get images as an array from a API I need to transcode them to Base64 to store in a local DB.
This is based on the Gravity Forms API, Wordpress, PHP, mySQL, (LAMP) etc.
<?php
$images = array();
$body = array();
$imagesDecoded = array();
$imgUrls = array(
'1' => 'bg.jpg',
'2' => 'meeting.jpg',
'3' => 'testimonial.jpg',
'4' => 'works.jpg',
);
$imgUrls = array_map(function($el) {
return 'http://orlandojoes.co.uk/rimos/images/' . $el;
}, $imgUrls);
print'<pre>';
print_r($imgUrls);
print'</pre>';
foreach ($imgUrls as $image) {
$data = file_get_contents($imgUrls);
$data = base64_encode($imgUrls);
array_push($body, $data);
}
print '<pre>';
print_r ($body);
print '<pre>';
foreach ($body as $bodyimage) {
$dataDec = base64_decode($bodyimage);
array_push($imagesDecoded, $dataDec);
}
print '<pre>';
print_r ($imagesDecoded);
print '<pre>';
This is the output from when I run this code now:
Array
(
[ptSignature] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[pSignature] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[witness1Signature] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[witness2Signature] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
Array
(
[0] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9iZy5qcGc=
[1] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9tZWV0aW5nLmpwZw==
[2] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy90ZXN0aW1vbmlhbC5qcGc=
[3] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy93b3Jrcy5qcGc=
)
Array
(
[0] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[1] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[2] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[3] => http://orlandojoes.co.uk/rimos/images/works.jpg
)

You have two bugs in your code.
$data = file_get_contents($imgUrls); // This is an array of URLs
$data = base64_encode($imgUrls); // You encode the URLs here!
Should be:
$data = file_get_contents($image); // $image instead of $imgUrls
$data = base64_encode($data); // $data instead of $imgUrls
Or simply:
$data = base64_encode(file_get_contents($image));
Side note, you don't need array_push() in your code, it's typically only needed if you want to push more than one item at one time. So, you can change it to just:
$body[] = $data;

Related

How can I put my html / php text-json output in a variable?

I want to write a script for an api from a website. This website gives you the data in a text that is like a json text.
[ { "nickname":"dieeeeeeter", "votes":"9" }, { "nickname":"Honk", "votes":"9" },
I just want to add the nickname and the number of votes into my database, so I delete (replace) everything else.
$data = file_get_contents($filename);
$data = str_replace('"', '', $data);
$data = str_replace(':', '', $data);
$data = str_replace('{}', '', $data);
$data = str_replace('nickname', '', $data);
$data = str_replace('votes', '', $data);
So now my text output looks like this
{ Honk, 9 }, { dieeeeeeter, 9 }
But I don't know how I can but my data into a variable like "$username".
Can you help me ?
I suggest to use json_decode php function to convert json string to array and loop the array to get the values and insert them to database.
$json_string = '[ { "nickname":"dieeeeeeter", "votes":"9"}, { "nickname":"Honk", "votes":"9"}]';
$data_array = json_decode($json_string ,true);
print_r($data_array );
foreach($data_array as $data){
$nickname = trim($data['nickname']);
$votes = trim($data['votes']);
// insert query goes here
}
Out put of array will be like this
Array
(
[0] => Array
(
[nickname] => dieeeeeeter
[votes] => 9
)
[1] => Array
(
[nickname] => Honk
[votes] => 9
)
)

Php array and json

help me to convert the following array in to json.
I tried to convert the array.
Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)
[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)
current result for the following code is
public function searchOrder($idx, $data) {
if (!empty($data)) {
$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}
now i got the result is like
[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]
But I need the result as follows
[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]
Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.
Note: Your desired JSON is not a valid format, you can't use same index
for two data.
Online Example: https://3v4l.org/kdPDI
$arr = array(
array(
'c_code' => '200001',
'itemname' => '303 10CAP',
'c_pack_code' => 'PK0075',
'c_web_img_link' => ''
),
array(
'c_code' => '200005',
'itemname' => '3P 4TAB',
'c_pack_code' => '',
'c_web_img_link' => ''
)
);
$res1 = array();
$res2 = array();
foreach($arr as $val){
$res1['c_code'][] = $val['c_code'];
$res1['itemname'][] = $val['itemname'];
$res2['c_pack_code'][] = $val['c_pack_code'];
$res2['c_web_img_link'][] = $val['c_web_img_link'];
}
$out = array(array_merge($res1, $res2));
echo json_encode($out);

Reduce URL strings with no duplicates

I have an array that looks like the following...
$urls = array(
"http://www.google.com",
"http://www.google.com/maps",
"http://www.google.com/mail",
"https://drive.google.com",
"https://www.youtube.com",
"https://www.youtube.com/feed/subscriptions",
"https://www.facebook.com/me",
"https://www.facebook.com/me/friends"
);
I find this hard to explain but I want to break this array down to only show the reduced URLs with no duplicates, so it looks like this...
$urls = array(
"http://www.google.com",
"https://drive.google.com",
"https://www.youtube.com",
"https://www.facebook.com/me"
);
Notice the last URL in the second array still has it's path. This is because I want still want to show the lowest level paths
Based on #Tim's answer
foreach ($urls as &$url) {
$url_parts = parse_url($url);
$url = $url_parts["scheme"]."://".$url_parts["host"];
}
$urls = array_unique($urls);
Just sort the array in reverse order, and create an array indexed by host:
$urls = array(
"http://www.google.com",
"http://www.google.com/maps",
"http://www.google.com/mail",
"https://drive.google.com",
"https://www.youtube.com",
"https://www.youtube.com/feed/subscriptions",
"https://www.facebook.com/me",
"https://www.facebook.com/me/friends"
);
rsort($urls);
$return = [];
foreach($urls as $url) {
$host = parse_url($url, PHP_URL_HOST);
$return[$host] = $url;
}
$return = array_values($return); // To remove array keys, if desired.
The reverse-ordered urls array would be:
Array
(
[0] => https://www.youtube.com/feed/subscriptions
[1] => https://www.youtube.com
[2] => https://www.facebook.com/me/friends
[3] => https://www.facebook.com/me
[4] => https://drive.google.com
[5] => http://www.google.com/maps
[6] => http://www.google.com/mail
[7] => http://www.google.com
)
Since the last entry (per host name) in the sorted array is the one that you want, and it deliberately clobbers any existing array value, this would output:
Array
(
[www.youtube.com] => https://www.youtube.com
[www.facebook.com] => https://www.facebook.com/me
[drive.google.com] => https://drive.google.com
[www.google.com] => http://www.google.com
)
Try this:
$result = array();
array_push($result, $urls[0])
for($i=1; $i<count($urls); $i++)
{
$repeat = false;
foreach($result as $res)
{
if(strpos($urls[i], $res))
{
$repeat = true;
break;
}
}
if(!repeat)
array_push($result, $urls[i])
}
return $result;

JSON array start with several Array

I'm trying to create JSON feed from one site which i want to decode on another. The problem is there seem to be to many array[0], so it is hard to loop through it and count how many objects there are.
How can i do this encode and decode without getting all these arrays, to make it easier to count the amount of objects and loop through it.
at the moment i'm encoding it like this:
$data = array();
foreach ($posts as $post) {
$r = str_replace("\n",'', shorten_txt($post->post_content, 500));
$n = str_replace("\r", '', $r);
$post_data = array(
'title' => get_the_title($post->ID),
'link' => get_permalink($post->ID),
'image' => catch_that_image(),
'content' => $n,
'time' => get_the_date( $d)." ". get_the_time( $d));
$data[] = (array('item' => $post_data));
}
echo json_encode($data);
This gives this output:
[
{
item: {
title: "Hello world!",
link: "http://URL/wordpress/?p=1",
image: "http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png",
content: "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
time: "April 17, 2014 5:32 pm"
}
}
]
When i decode this i get this:
Array ( [0] => Array ( [item] => Array( [title] => Hello world! [link] => http://URL/wordpress/?p=1 [image] => http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png [content] => Welcome to WordPress. This is your first post. Edit or delete it, then start blogging! Jeg elsker kage [time] => April 17, 2014 5:32 pm ) ) )
The decode code:
$json_string = 'http://95.85.11.40/wordpress/?page_id=20';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
print_r($obj);
If you don't want those array[0] bits, then don't create a 2D array:
$data[] = (array('item' => $post_data));
Should then be:
$data[] = $post_data;
Your current statement read as _add to array $data an array, with 1 key: "item", whereas my version just says: add to $data the value of $post_data.
loping oiver decoded data:
$data = json_decode(file_get_contents($jsonFile), true);
foreach ($data as $idx => $item)
{
echo 'This is item number ', $idx +1, PHP_EOL;
print_r($item);
}

Bidimensional array generated dynamically

I'm working with dynamic data, so I'm trying to put that data into a bidimensional array.
I need a structure like this:
$array['something1'] = array ( 'hi1' => 'there1' , 'hi2' => 'there2' );
All this data is dynamically generated by a foreach, ex.:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
// set data
$items[$columns[0]] = array ( $columns[1] => $columns[2] );
}
How Can I do the previously described?
Right now the script is stepping over the previous key getting something like this:
$array['something1'] = array ( 'hi2' => 'there2' );
I hope you can help me.
Thanks.
The problem is that you are overwriting the value for the key when it already exists. You should modify to something like:
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
$outer_array_key = $columns[0];
$key = $columns[1];
$value = $columns[2];
// set data
$items[$outer_array_key][$key] = $value;
}
Here is how it can be done:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
$newlist =array();
foreach($list as $k=>$v){
$items = explode(';',$v);
$newlist[$items[0]][$items[1]]=$items[2];
}
echo "<pre>";
print_r($newlist);
echo "</pre>";
//output
/*
Array
(
[something] => Array
(
[hi1] => there1
[hi2] => there2
)
)*/
?>
Change your set data with something like this :
if(!array_key_exists($columns[0], $items))
$items[$columns[0]] = array();
$items[$columns[0]][$columns[1]] = $columns[2];

Categories