Error Array to String JPG Error - php

I want to fetch a string to find the URLs, store them in an array and use them to build an custome output. The problem is that I get an error that I have a string to array conversion.
NOTICE Array to string conversion on line number 21 JPEG (Array)
Can some help me, is there another way to get the URL which is stored in the array?
function getURLSfromStringToImages($string) {
$regex = '/https?\:\/\/[^" ]+/i';
preg_match_all($regex, $string, $matches);
//($matches[0]);
$tmp = '';
$tmpArray = $matches;
if ( is_array( $tmpArray ) ) {
$size = count( $tmpArray ); //array size by using count() function
$index = 0;
while ( $index < $size ) {
$tmp .= '<anhang location="REMOTE" gruppe="BILD">' . "\n"
. '<format>JPEG</format>' . "\n"
. '<daten>' . "\n"
. '<pfad>' . "($tmpArray[$index])" . '</pfad>' . "\n"
. '</daten>' . "\n"
. '</anhang>' . "\n \n";
$index ++;
}
}
echo $tmp;
}
$urls = getURLSfromStringToImages('a:3:{i:0;a:9:{s:22:"real_estate_floor_name";s:7:"Karnten";s:23:"real_estate_floor_price";s:0:"";s:31:"real_estate_floor_price_postfix";s:0:"";s:22:"real_estate_floor_size";s:0:"";s:30:"real_estate_floor_size_postfix";s:0:"";s:26:"real_estate_floor_bedrooms";s:0:"";s:27:"real_estate_floor_bathrooms";s:0:"";s:29:"real_estate_floor_description";s:0:"";s:23:"real_estate_floor_image";a:2:{s:2:"id";s:4:"4243";s:3:"url";s:70:"https://www.immo-verteiler.de/wp-content/uploads/2018/06/grundriss.jpg";}}i:1;a:9:{s:22:"real_estate_floor_name";s:6:"sterer";s:23:"real_estate_floor_price";s:0:"";s:31:"real_estate_floor_price_postfix";s:0:"";s:22:"real_estate_floor_size";s:0:"";s:30:"real_estate_floor_size_postfix";s:0:"";s:26:"real_estate_floor_bedrooms";s:0:"";s:27:"real_estate_floor_bathrooms";s:0:"";s:29:"real_estate_floor_description";s:0:"";s:23:"real_estate_floor_image";a:2:{s:2:"id";s:4:"4211";s:3:"url";s:76:"https://www.immo-verteiler.de/wp-content/uploads/2018/06/Hotel-Goestling.jpg";}}i:2;a:9:{s:22:"real_estate_floor_name";s:13:"lkjölkjölkj";s:23:"real_estate_floor_price";s:0:"";s:31:"real_estate_floor_price_postfix";s:0:"";s:22:"real_estate_floor_size";s:0:"";s:30:"real_estate_floor_size_postfix";s:0:"";s:26:"real_estate_floor_bedrooms";s:0:"";s:27:"real_estate_floor_bathrooms";s:0:"";s:29:"real_estate_floor_description";s:0:"";s:23:"real_estate_floor_image";a:2:{s:2:"id";s:4:"3907";s:3:"url";s:66:"https://www.immo-verteiler.de/wp-content/uploads/2018/05/klein.jpg";}}}');
print_r($urls);

You need two loops
while ( $index < $size ) {
foreach($tmpArray[$index] as $path)
$tmp .= '<anhang location="REMOTE" gruppe="BILD">' . "\n"
. '<format>JPEG</format>' . "\n"
. '<daten>' . "\n"
. '<pfad>' . $path . '</pfad>' . "\n"
. '</daten>' . "\n"
. '</anhang>' . "\n \n";
$index ++;
}
also, I suggest you use the heredoc syntax: https://www.php-space.info/php/space/heredoc-syntax.php

Matches are obtained into an array of arrays. You need to only grab full match values, that are stored in $matches[0].
Hence, use
$tmpArray = $matches[0]; // not $tmpArray = $matches;
Also, just use $tmpArray[$index] instead of "($tmpArray[$index])".
See the PHP demo.

Related

Adding custom masks to phone numbers

So i'm creating a simple function to mask phone numbers. My phone numbers have a 9 digits and i want preg_replace them with a given mask like 2-2-2-1-2 or 3-2-2-2 and etc.
I tried this:
$mask = explode('-', '3-2-2-2');
$pattern = '';
$replace = '';
foreach ($mask as $key => $value) {
if ($key == 0) {
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$replace = '$' . ++$key . '-';
continue;
}
if ($key == count($mask) - 1) {
$pattern .= '?(\d{' . $value . '})/';
$replace .= '$' . ++$key;
break;
}
$pattern .= '?(\d{' . $value . '})[- ]';
$replace .= '$' . ++$key . '-';
}
return preg_replace($pattern, $replace, '902000810');
and the result is 902-00-08-10. Sometimes getting error preg_replace(): No ending delimiter '/' found. How can i refactor this to not getting errors?
Assuming:
$num = '902000810';
$mask = explode('-', '3-2-2-2');
There're other ways than using regex to format a phone number from the mask.
using formatted strings:
$maskPH = array_map(fn($i) => "%{$i}s", $mask);
$formatI = implode('', $maskPH);
$formatO = implode('-', $maskPH);
$result = vsprintf($formatO, sscanf($num, $formatI));
using unpack:
$format = array_reduce($mask, function ($c, $i) {
static $j = 0;
return "{$c}A{$i}_" . $j++ . "/";
});
$result = implode('-', unpack($format, $num));
preg_replace(): No ending delimiter '/' found
means that your pattern does not terminate with a / as last character.
But all three patterns lack proper formatting:
You should modify them accordingly.
From:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]';
$pattern .= '?(\d{' . $value . '})/';
$pattern .= '?(\d{' . $value . '})[- ]';
To:
$pattern = '/\(?(\d{' . $value . '})\)?[- ]/';
$pattern .= '/?(\d{' . $value . '})/';
$pattern .= '/?(\d{' . $value . '})[- ]/';

PHP line break inside of cell remove qoute

This is my PHP
$val = "";
foreach($data as $v){
$val .= '"' . $v . "\n" . '"';
}
The result is
//this is inside of cell
sample
"sample
"sample
This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.
EDIT
This is the result of my code
This is what I want
Just Remove some part of your code, you will get solution:
$val = "";
foreach($data as $v){
$val .= $v . "\n";
}
Just try (Maintaining line break in excel):
$val = "";
foreach($data as $v){
$val .= $v . "<br style='mso-data-placement:same-cell;' />";
}
Somthing like this should do the trick
$i = 0
foreach($data as $v){
$val .= '"' . $v . "\n" . (count($data) !== $i) ? '"' : '';
$i++;
}
I think you can use the php function trim like this:
$val = "";
foreach($data as $v){
if( ''==$val) {
$val .= trim('"' . $v . "\n" . '"','"');
}else{
$val .= '"' . $v . "\n" . '"','"';
}
}
$val .= '"' . $v . "</br>" . '"';
$val=str_replace('"','',$val);
I think this is what you are looking for inside your loop. It will remove every double quote.
Well there you go :
$data = ['sample','sample','sample'];
$val = "";
foreach($data as $v){
$val .= $v . "\n" ;
}
Then you simply use fputcsv() like this :
$fp = fopen('file.csv', 'w');
fputcsv($fp, [$val]);
And you get the result you want :
The answer to my question is
$val = "";
foreach($data as $v){
$val .= $v . "\n";
}
$val = '"'. $val .'"';
I need to add the '"' outside of the loop.

Using array_map to make an alternative to print_r to produce a 'cleaner' output

I need a cleaner output than print_r gives me
an array like
$array = array(1,2,3,"four"=>array(4.1,4.2));
should print out somthing like this
0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2
I've come up with this, but the array_map does not return what I expected
function print_array($array) {
$string = "";
foreach ( $array as $key => $value ) {
if (is_array ( $value )) {
$string .= "[" . $key . "]\r\n" . array_map ( 'print_array', $value );
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
The output from this is
0: 1
1: 2
2: 3
[four]
Array
my array_map use is apparently wrong can anyone enlighten me?
Use this it may help you , call your function recursively if value is an array.
<?php
function print_array($array) {
$string = "";
foreach ( $array as $key => $value ) {
if (is_array ( $value )) {
$string .= "[" . $key . "]\r\n" . print_array($value );
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
$array = array(1,2,3,"four"=>array(4.1,4.2));
print_r(print_array($array));
?>
Output
0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2
This way of printing doesn't really need array_map. The following uses the biggest part of your own function. It is untested but should help you in the right direction.
function print_array($source) {
$string = "";
foreach ($sorce as $key => value) {
if (is_array($value)) {
$string .= $key . ": array (\r\n";
$string .= print_array($value);
$string .= ")\r\n";
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
echo print_array($myArray);

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

PHP Array Declaration

for ($k = 0; $k < $count; $k++) {
$master[$k] = $namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k];
}
I'd like to declare a new array and set values from other arrays already declared. I thought I could just loop through the keys and set the values but this doesn't work for me.
Full code below. I'm parsing yellow pages search results and trying to output search results into a csv file. In the code below I removed the loop and only added a few values to the array to make sure my bug wasn't something else.
<?php
// include required functions
include('simple_html_dom.php');
$url = "http://www.yellowpages.com/" . $_POST['city'] . '-' . $_POST['state'] . '-' . $_POST['postalcode'] . '/' . $_POST['category'] . '?g=' . $_POST['city'] . '%2C+' . $_POST['state'] . '+' . $_POST['postalcode'] . '&q=' . $_POST['category'];
// get DOM from URL
$html = file_get_html($url);
// find all business name
foreach($html->find('h3.business-name') as $name)
//echo $name->innertext . '<br />';
$namearray[] = $name->innertext;
// find all business street address
foreach($html->find('span.street-address') as $street)
//echo $street->innertext . '<br />';
$streetarray[] = $street->innertext;
// find all business city
foreach($html->find('span.locality') as $locality)
//echo $locality->innertext . '<br />';
$localityarray[] = $locality->innertext;
// find all business state
foreach($html->find('span.region') as $region)
//echo $region->innertext . '<br />';
$regionarray[] = $region->innertext;
// find all business postal code
foreach($html->find('span.postal-code') as $postalcode)
//echo $postalcode->innertext . '<br />';
$postalcodearray[] = $postalcode->innertext;
// find all business phone
foreach($html->find('span.business-phone') as $phone)
//echo $phone->innertext . '<br />';
$phonearray[] = $phone->innertext;
?>
<p>Search results for: <?php echo $_POST['category'] . ' ' . $_POST['city'] . ' ' . $_POST['state'] . ' ' . $_POST['postalcode']; ?></p>
<?php
// Output results
$count = count($namearray);
for ($i = 0; $i < $count; $i++) {
echo $namearray[$i] . '<br />';
echo $streetarray[$i] . '<br />';
echo $localityarray[$i] . ',' . $regionarray[$i] . ' ' . $postalcodearray[$i] . '<br />';
echo $phonearray[$i] . '<br />' . '<br />';
}
$list = array (
array($namearray[0], $streetarray[0], $localityarray[0], $regionarray[0], $postalcodearray[0], $phonearray[0]),
array($namearray[1], $streetarray[1], $localityarray[1], $regionarray[1], $postalcodearray[1], $phonearray[1]),
array($namearray[2], $streetarray[2], $localityarray[2], $regionarray[2], $postalcodearray[2], $phonearray[2]),
array($namearray[3], $streetarray[3], $localityarray[3], $regionarray[3], $postalcodearray[3], $phonearray[3])
);
$fp = fopen('hrpsearch.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Try:
$master = array();
for ($k = 0; $k < $count; $k++) {
$master[$k] = array
( $namearray[$k]
, $streetarray[$k]
, $localityarray[$k]
, $regionarray[$k]
, $postalcodearray[$k]
, $phonearray[$k]
);
}
This will create a new two-dimensional array for you with associated keys for every child array.
Try
for($k = 0; $k < $count; $k++) {
$master[$k] = array(
$namearray[$k],
$streetarray[$k],
$localityarray[$k],
$regionarray[$k],
$postalcodearray[$k],
$phonearray[$k]
);
}
Maybe do you just want to achieve this?
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
I would suggest using instead:
$master[$k]['name'] = $namearray[$k];
$master[$k]['street'] = $streetarray[$k];
...
The retrieval of the data will be more readable.
I think #DaveRandom's answer is what (I imply) you are looking for.
Since a PHP array can be of any type (scalar, array, object, etc.), you need to tell it you are assigning an array with the construct array().
The end result would be:
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
Try this
for ($k = 0; $k < $count; $k++) {
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
}
or is better to create associative array
for ($k = 0; $k < $count; $k++) {
$master[$k] = array('name'=>$namearray[$k],
'street'=>$streetarray[$k],
'city'=>$localityarray[$k],
'region'=>$regionarray[$k],
'postalCode'=>$postalcodearray[$k],
'phone'=>$phonearray[$k]);
}
You also need to check if your array elements are not empty or just put # befor array element like 'name'=>#$namearray[$k]. It will remove any warning if element doesn't exist.

Categories