Hello I'm trying to get this information from an HTML page but it doesn't have element,class, nothing it just have <pre>all content</pre> how can I extract the value from "validTo"? Information below
It is not a JSON FILE, its just the content of the web page.
[serialNumber] => 984924526890779987
[validFrom] => 180515204024Z
[validTo] => 180807195300Z
[validFrom_time_t] => 1526416824
PHP Code:
<?php
$url = "https://www.google.es";
$orignal_parse = parse_url($url, PHP_URL_HOST);
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => TRUE)));
$read = stream_socket_client("ssl://".$orignal_parse.":443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $get);
$cert = stream_context_get_params($read);
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
echo $certinfo
Something like this will work if the page is formatted the way you described.
// get the webpage - replace your.url with the actual webpage address
$html = file('your.url',FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES) ;
// get your value
foreach($html as $line) {
$result = strpos($line,'[validTo]') ;
if (false !== $result) {
$temp = explode('=>', $line) ;
$validTo = trim($temp[1]) ;
break ;
}
}
Consider your file has this content
file.html
[serialNumber] => 984924526890779987
[validFrom] => 180515204024Z
[validTo] => 180807195300Z
[validFrom_time_t] => 1526416824
Now this will extract the info and put it into an array named $arr. Access each by using that array.
<?php
$data = file_get_contents('http://domain/file.html');
$arr = explode(PHP_EOL, $data);
echo $arr[0];
?>
Hi you can extract more info from a string by using Regex.
<?php
$string = "
<pre>
[serialNumber] => 984924526890779987
[validFrom] => 180515204024Z
[validTo] => 180807195300Z
[validFrom_time_t] => 1526416824
</pre>
";
preg_match('/\[validTo\].[\=\>].*[0-9a-zA-Z]/', $string, $values, PREG_OFFSET_CAPTURE);
print_r($values);
The Result was:
Array
(
[0] => Array
(
[0] => [validTo] => 180807195300Z
[1] => 97
)
)
Related
I am new to PHP and working to get some results but failing to achieve my target. I have text file which contains data like this,
APAC|AU|enable|SYD1925|8|20150929|WORKING
APAC|AU|disable|ADL7235|3|20120123|RESIGNED
APAC|NZ|disable|NZ1356|6|20110123|RESIGNED
APAC|NZ|enable|NZ1356|3|20130123|WORKING
I am trying to search "AU" && "enable" for this text, line by line and I am a bit successful in it. Here is my Code example;
public function scan1()
{
$file = FCPATH.'uploads/example.txt';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
$search1 = "AU";
$search2 = "enable";
$lines = file($file);
foreach($lines as $line)
{
if(stristr($line,$search1) && stristr($line,$search2))
echo $line;
}
}
Now, I am trying to explode/split output data and assign variable / array to save in database but I am failing to do so, can someone please help or give me some direction to achieve this. Thank you
Please show us your_table scheme.
If '$db' is a handle of the db connection :
foreach($lines as $line)
{
if(stristr($line,$search1) && stristr($line,$search2))
{
$arr = explode("|", $line);
$query = "INSERT INTO your_table VALUES ('".$arr[0]."', '".$arr[1]."', '".$arr[2]."', '".$arr[3]."', '".$arr[4]."', '".$arr[5]."')";
$db->query($query);
}
}
First, obtain the file contents with file_get_contents:
$str = file_get_contents(FCPATH.'uploads/example.txt');
Then, use the regex (preg_match_all) to find all portion of text you're looking for:
preg_match_all("/APAC\\|(\w{2}\\|\w+)/", $str, $matches);
Then adapt the array so the 'AU' and 'enabled' are separated (array_map, explode):
$matches = array_map(function ($v) { return explode('|', $v); }, $matches[1]);
So, print_r($matches); returns:
Array
(
[0] => Array
(
[0] => AU
[1] => enable
)
[1] => Array
(
[0] => AU
[1] => disable
)
[2] => Array
(
[0] => NZ
[1] => disable
)
[3] => Array
(
[0] => NZ
[1] => enable
)
)
Finally, the foreach loop:
foreach($matches as $k => $kv)
{
$search1 = $kv[0]; // AU
$search2 = $kv[1]; // enabled
}
This works as expected:
public function scan1()
{
$file = FCPATH.'uploads/example.txt';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
$search1 = "AU";
$search2 = "enable";
$lines = file($file);
foreach($lines as $line)
{
if(strpos($line,$search1) !== false && strpos($line,$search2) !== false)
echo $line;
}
}
using strpos function for detection.
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);
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;
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;
I'm not even sure how to begin wording this question, but basically, I have an array, that looks like this:
Array
(
[0] => /
[1] => /404/
[2] => /abstracts/
[3] => /abstracts/edit/
[4] => /abstracts/review/
[5] => /abstracts/view/
[6] => /admin/
[7] => /admin/ads/
[8] => /admin/ads/clickcounter/
[9] => /admin/ads/delete/
[10] => /admin/ads/edit/
[11] => /admin/ads/list/
[12] => /admin/ads/new/
[13] => /admin/ads/sponsordelete/
[14] => /admin/ads/sponsoredit/
[15] => /admin/ads/sponsornew/
[16] => /admin/ads/stats/
[17] => /admin/boilerplates/
[18] => /admin/boilerplates/deleteboiler/
[19] => /admin/boilerplates/editboiler/
[20] => /admin/boilerplates/newboilerplate/
[21] => /admin/calendar/event/add/
[22] => /admin/calendar/event/copy/
)
And I need to 'reduce' / 'process' it into an array that looks like this:
Array
(
[''] => Array()
['404'] => Array()
['abstracts'] => Array
(
[''] => Array()
['edit'] => Array()
['review'] => Array()
['view'] => Array()
)
['admin'] => Array
(
['ads'] => Array
(
[''] => Array()
['clickcounter'] => Array()
['delete'] =>Array()
['edit'] => Array()
)
)
.....
.....
)
That, if manually initialized would look something like this:
$urlTree = array( '' => array(),
'404' => array(),
'abstracts'=> array( '' => array(),
'edit' => array(),
'review'=> array(),
'view' => array() ),
'admin' => array( 'ads'=> array( '' => array(),
'clickcounter'=> array(),
'delete' => array(),
'edit' => array() ) )
);
I usually stray away from asking straight up for a chunk of code on SO, but does anyone perhaps have any advice / code that can traverse my array and convert it to a hierarchy?
EDIT: Here is the bit I have right now, which, I know is pitifully small, I'm just blanking out today it seems.
function loadUrlData()
{
// hold the raw data, /blah/blah/
$urlData = array();
$res = sql::query( "SELECT DISTINCT(`url`) FROM `pages` ORDER BY `url` ASC" );
while( $row = sql::getarray( $res ) )
{
$urlData[] = explode( '/', substr( $row['url'], 1, -1 ) );
}
// populated, eventually, with the parent > child data
$treeData = array();
// a url
foreach( $urlData as $k=> $v )
{
// the url pieces
foreach( $v as $k2=> $v2 )
{
}
}
// $treeData eventually
return $urlData;
}
Looks rather easy. You want to loop through all lines (foreach), split them into parts (explode), loop through them (foreach) and categorize them.
Since you don't like asking for a chunk of code, I won't provide any.
Update
A very nice way to solve this is to reference the $urlTree (use &), loop through every part of the URL and keep updating a variable like $currentPosition to the current part in the URL tree. Because you use &, you can simply edit the array directly while still using a simple variable.
Update 2
This might work:
// a url
foreach( $urlData as $k=> $v )
{
$currentSection = &$treeData;
// the url pieces
foreach( $v as $k2=> $v2 )
{
if (!isset($currentSection[$v2])) {
$currentSection[$v2] = array();
}
$currentSection = &$currentSection[$v2];
}
}
I know you didn't ask for a chunk of code, but I'd just call this a petit serving:
$map = array();
foreach($urls as $url) {
$folders = explode('/', trim($url, '/'));
applyChain($map, $folders, array());
}
function applyChain(&$arr, $indexes, $value) { //Here's your recursion
if(!is_array($indexes)) {
return;
}
if(count($indexes) == 0) {
$arr = $value;
} else {
applyChain($arr[array_shift($indexes)], $indexes, $value);
}
}
It's fairly simple. We separate each url into its folders (removing trailing and leading slashes) and then work our way down the array chain until we reach the folder mentioned in the URL. Then we place a new empty array there and continue to the next URL.
My version:
$paths = array(
0 => '/',
1 => '/404/',
2 => '/abstracts/',
3 => '/abstracts/edit/',
4 => '/abstracts/review/',
5 => '/abstracts/view/',
6 => '/admin/',
7 => '/admin/ads/',
// ....
);
$tree = array();
foreach($paths as $path){
$tmp = &$tree;
$pathParts = explode('/', rtrim($path, '/'));
foreach($pathParts as $pathPart){
if(!array_key_exists($pathPart, $tmp)){
$tmp[$pathPart] = array();
}
$tmp = &$tmp[$pathPart];
}
}
echo json_encode($tree, JSON_PRETTY_PRINT);
https://ideone.com/So1HLm
http://ideone.com/S9pWw
$arr = array(
'/',
'/404/',
'/abstracts/',
'/abstracts/edit/',
'/abstracts/review/',
'/abstracts/view/',
'/admin/',
'/admin/ads/',
'/admin/ads/clickcounter/',
'/admin/ads/delete/',
'/admin/ads/edit/',
'/admin/ads/list/',
'/admin/ads/new/',
'/admin/ads/sponsordelete/',
'/admin/ads/sponsoredit/',
'/admin/ads/sponsornew/',
'/admin/ads/stats/',
'/admin/boilerplates/',
'/admin/boilerplates/deleteboiler/',
'/admin/boilerplates/editboiler/',
'/admin/boilerplates/newboilerplate/',
'/admin/calendar/event/add/',
'/admin/calendar/event/copy/');
$result = array();
foreach ($arr as $node) {
$result = magic($node, $result);
}
var_dump($result);
function magic($node, $tree)
{
$path = explode('/', rtrim($node, '/'));
$original =& $tree;
foreach ($path as $node) {
if (!array_key_exists($node, $tree)) {
$tree[$node] = array();
}
if ($node) {
$tree =& $tree[$node];
}
}
return $original;
}
<?php
$old_array = array("/", "/404/", "/abstracts/", "/abstracts/edit/", "/abstracts/review/", "/rrl/");
$new_array = array();
foreach($old_array as $woot) {
$segments = explode('/', $woot);
$current = &$new_array;
for($i=1; $i<sizeof($segments); $i++) {
if(!isset($current[$segments[$i]])){
$current[$segments[$i]] = array();
}
$current = &$current[$segments[$i]];
}
}
print_r($new_array);
?>
You might consider converting your text to a JSON string, then using json_decode() to generate the structure.