将PHP数组中的URL编码为Base64

时间:2015-12-18 19:41:48

标签: php wordpress gravity-forms-plugin

这是我的代码,我正在尝试将图像内容编码为base64,但我最终将URL作为base64字符串结束。

最后,我将图像作为数组从我需要的API转换为Base64以存储在本地数据库中。

这是基于Gravity Forms API,Wordpress,PHP,mySQL,(LAMP)等。

<?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>';

这是我现在运行此代码时的输出:

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
)

1 个答案:

答案 0 :(得分:0)

您的代码中有两个错误。

$data = file_get_contents($imgUrls); // This is an array of URLs
$data = base64_encode($imgUrls); // You encode the URLs here!

应该是:

$data = file_get_contents($image); // $image instead of $imgUrls
$data = base64_encode($data); // $data instead of $imgUrls

或者简单地说:

$data = base64_encode(file_get_contents($image));

旁注,您的代码中不需要array_push(),通常只有在您想要同时推送多个项目时才需要它。因此,您可以将其更改为:

$body[] = $data;