Link to home
Start Free TrialLog in
Avatar of Shamsul Kamal
Shamsul Kamal

asked on

How to convert PHP array into string ?

Hi,

I would like to request an assistant.

I have the following array output.


Array
(
    [result] => success
    [invoiceid] => 225792
    [invoicenum] => 
    [userid] => 29454
    [date] => 2017-04-10
    [duedate] => 2017-05-01
    [datepaid] => 2017-04-10 16:20:16
    [lastcaptureattempt] => 0000-00-00 00:00:00
    [subtotal] => 4.00
    [credit] => 0.00
    [tax] => 0.00
    [tax2] => 0.00
    [total] => 4.00
    [balance] => 0.00
    [taxrate] => 6.00
    [taxrate2] => 0.00
    [status] => Paid
    [paymentmethod] => fpx
    [notes] => 
    [ccgateway] => 
    [items] => Array
        (
            [item] => Array
                (
                    [0] => Array
                        (
                            [id] => 281093
                            [type] => 
                            [relid] => 0
                            [description] => Test Item 1
                            [amount] => 4.00
                            [taxed] => 0
                        )

                )

        )

    [transactions] => Array
        (
            [transaction] => Array
                (
                    [0] => Array
                        (
                            [id] => 156746
                            [userid] => 29454
                            [currency] => 0
                            [gateway] => fpx
                            [date] => 2017-04-10 16:20:16
                            [description] => Invoice Payment
                            [amountin] => 4.00
                            [fees] => 0.00
                            [amountout] => 0.00
                            [rate] => 1.00000
                            [transid] => 1704101601570658 Bank Auth No 02368983
                            [invoiceid] => 225792
                            [refundid] => 0
                        )

                )

        )

)

Open in new window



May i  know how to manipulate the data and convert into string ?

eg :

foreach($jsonData as $value) {

        
            $invoiceid  = $value['invoiceid'];
            $invoicedate  = $value['date'];
            $credit  = $value['credit'];
            $tax  = $value['tax'];
            $total  = $value['total'];
            $balance  = $value['balance'];
            $status  = $value['status'];
                         
                                          foreach ($value['items'] as $item) {
                  $content .= '<tr><td>Description</td><td>'.$item['description'].'</td></tr>';
                  $content .= '<tr><td>Amount</td><td>'.$item['amount'].'</td></tr>';
                                  }

}


Appreciates your assistant by providing sample from my output.

Thank you.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Can you explain what you mean by output to a string - what sort of string? In your sample above some of the data is going to rows in a table - what are you wanting to do with the string?
Avatar of Shamsul Kamal
Shamsul Kamal

ASKER

Hi,

Im sorry its actually convert to variable.

Eg: $invoiceid , etc

I will then construct the variable into tables.
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
But the data contains nested arrays - how do you want to handle those.

extract() will extract the top most variables - should those themselves be arrays you would need to either recursively call extract - which is dangerous - or need to decide how you are going to deal with them.

Personally I think extract is a terrible function as you have no control over variable creation, you could end up overwriting variables - I would strongly suggest you don't use it.

Rather describe what it is you want to do - and specifically how you want to deal with the nested arrays - how do you plan on using them. Describe what the output is you want to achieve - then we can be better placed to help you.
recursively call extract - which is dangerous
Anything can be "dangerous" if you do it wrong.  That's why we have flags and a prefix in the extract() function signature!  If you use those parts of the function you have perfect control over what will be injected into the symbol table.

Suggestion: Please use var_export() to print out the information posted in the original code snippet.  It looks like it might be a JSON string that has been decoded into a PHP array or object.  If you use var_export() you will get an executable representation of the PHP information.  You can post that in the code snippet and we can show you how to use it in a PHP program.
Hi,

Based on Ray Paseur advice, im able to solved the FIRST PART but not the SECOND PART :



$REQUEST = $jsonData;
$aVarToExtract = array(invoiceid, invoicedate, credit, tax, total, balance, status, items);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

//FIRST PART = OK 	
		  
		$content .= '<form method="post" action="" name="invoiceform"  onsubmit="return validateForm()">'; 
			
		$content .= '<table border="1" cellpadding="5" style="border-collapse: collapse;border: 1px solid #cacaca">';
		$content .= '<tr><td>Invoice ID</td><td>'.$invoiceid.'</td></tr>';
		$content .= '<tr><td>Invoice Date</td><td>'.$invoicedate.'</td></tr>';
		$content .= '<tr><td>Credit</td><td>'.$credit.'</td></tr>';
		$content .= '<tr><td>Tax</td><td>'.$tax.'</td></tr>';
		$content .= '<tr><td>Total</td><td>'.$total.'</td></tr>';
		$content .= '<tr><td>Balance</td><td>'.$balance.'</td></tr>';
	
	
// SECOND PART = NOT OK

		
		$content .= '<tr><th colspan="2" bgcolor="thistle">ITEMS</th></tr>';
		
		$itemarray=print_r($items);
		
		extract($items, EXTR_REFS);
       
       
    foreach ($items as $key => $value) {
    $this->$key = $key;
    
    $content .= '<tr><td>Description</td><td>'.$key->description.'</td></tr>';
    $content .= '<tr><td>Amount</td><td>'.$key->amount.'</td></tr>';

}
echo "$content";

Open in new window


Maybe because of the nested array that Julian mentioned ?

Can anybody help me ?
Does this information come from an API?  Can you post the original information that you get from the API?  It might be easier to look at the application in a more holistic view :-)
Hi,

Yes, it is from the API.

My code where SECOND PART not working are as follows :

<?


 $url = "http://www.xxxxxxx.com/billing/includes/api.php"; # URL to WHMCS API file goes here
 $username = "sksatech"; # Admin username goes here
 $password = "xxxxxx"; # Admin password goes here
 $getinvoiceid = $_POST['invoiceid'];

 $postfields = array();
 $postfields["username"] = $username;
 $postfields["password"] = md5($password);
 $postfields["action"] = "getinvoice";
 $postfields["invoiceid"] = "228567";
 

 
 

 $query_string = "";

 foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_TIMEOUT, 30);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
 
 $xml = curl_exec($ch);
 if (curl_error($ch) || !$xml) $xml = '<whmcsapi><result>error</result>'.
 '<message>Connection Error</message><curlerror>'.
 curl_errno($ch).' - '.curl_error($ch).'</curlerror></whmcsapi>';
 curl_close($ch);


//	echo "<script>alert('$xml');</script>";
 

$jsonData = json_decode($xml, true);
 
//print_r($jsonData); 


// FIRST PART - WORKING FINELY	


$REQUEST = $jsonData;
$aVarToExtract = array(invoiceid, invoicedate, credit, tax, total, balance, status, items);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));



	
		  
		$content .= '<form method="post" action="" name="invoiceform"  onsubmit="return validateForm()">'; 
			
		$content .= '<table border="1" cellpadding="5" style="border-collapse: collapse;border: 1px solid #cacaca">';
		$content .= '<tr><td>Invoice ID</td><td>'.$invoiceid.'</td></tr>';
		$content .= '<tr><td>Invoice Date</td><td>'.$date.'</td></tr>';
		$content .= '<tr><td>Credit</td><td>'.$credit.'</td></tr>';
		$content .= '<tr><td>Tax</td><td>'.$tax.'</td></tr>';
		$content .= '<tr><td>Total</td><td>'.$total.'</td></tr>';
		$content .= '<tr><td>Balance</td><td>'.$balance.'</td></tr>';
		
		
		if ($status == "Unpaid"){
			
		
			$statuscolor="<font color=red>".$status."</font>&nbsp;&nbsp;<input type='hidden' name='invoiceid' value='".$invoiceid."' >&nbsp;&nbsp;<input type='text' class='center' size='5' name='balance' value='".$balance."'>&nbsp;&nbsp;<input type='text' size='20' placeholder='Transaction ID'  class='center' name='transid' value='' >&nbsp;&nbsp;<input type='submit' value='Pay' id='myButton' name='addPayment' class='button'>";
			$content .= '<tr><td>Invoice Status</td><td><b>'.$statuscolor.'</b></td></tr>';
		}

		if ($status == "Paid"){$statuscolor="<font color=green>".$status."</font>";
		$content .= '<tr><td>Invoice Status</td><td><b>'.$statuscolor.'</b></td></tr>';
		}
		
		
		
// SECOND PART - NOT WORKING		
		
		
	
		$content .= '<tr><th colspan="2" bgcolor="thistle">ITEMS</th></tr>';

		
		extract($items, EXTR_REFS);
      foreach ($items as $key => $value) {
           $this->key = $key;

 			$content .= '<tr><td>Description</td><td>'.$key->description.'</td></tr>';
			$content .= '<tr><td>Amount</td><td>'.$key->amount.'</td></tr>';

      }
      
      
//		foreach ($items as $item) {
//			$content .= '<tr><td>Description</td><td>'.$itemarray.'</td></tr>';
//			$content .= '<tr><td>Amount</td><td>'.$item['amount'].'</td></tr>';
//		}
		
		$content .= '</table>';
		$content .= '</form>';  


echo "$content";


?>

Open in new window



The OUTPUT for $jsonData are as follows :

Array
(
    [result] => success
    [invoiceid] => 228567
    [invoicenum] => 
    [userid] => 19577
    [date] => 2017-05-18
    [duedate] => 2017-07-10
    [datepaid] => 2017-05-18 11:49:10
    [lastcaptureattempt] => 0000-00-00 00:00:00
    [subtotal] => 139.90
    [credit] => 0.00
    [tax] => 8.39
    [tax2] => 0.00
    [total] => 148.29
    [balance] => 0.00
    [taxrate] => 6.00
    [taxrate2] => 0.00
    [status] => Paid
    [paymentmethod] => banktransfer
    [notes] => *price promotion renew mynic
    [ccgateway] => 
    [items] => Array
        (
            [item] => Array
                (
                    [0] => Array
                        (
                            [id] => 284674
                            [type] => Hosting
                            [relid] => 23014
                            [description] => Linux-Standard-Plan - xxx.com.my (10/07/2017 - 10/07/2018)160.00
                            [amount] => 80.00
                            [taxed] => 1
                        )

                    [1] => Array
                        (
                            [id] => 284675
                            [type] => Domain
                            [relid] => 34730
                            [description] => Domain Renewal - xxx.com.my - 1 Year/s (10/07/2017 - 10/07/2018)
                            [amount] => 59.90
                            [taxed] => 1
                        )

                )

        )

    [transactions] => Array
        (
            [transaction] => Array
                (
                    [0] => Array
                        (
                            [id] => 158331
                            [userid] => 19577
                            [currency] => 0
                            [gateway] => banktransfer
                            [date] => 2017-05-18 11:49:10
                            [description] => Invoice Payment
                            [amountin] => 148.29
                            [fees] => 0.00
                            [amountout] => 0.00
                            [rate] => 1.00000
                            [transid] => XEV-217-87171
                            [invoiceid] => 228567
                            [refundid] => 0
                        )

                )

        )

)

Open in new window



Thank you.
Please use var_export($jsonData) and post that in the code snippet, thanks.

PHP var_export() produces something we can copy and install in a PHP script.  PHP print_r() is fine for looking at the data, but it requires a lot of hand work to turn print_r() information back into a PHP data structure.
Hi,

The following is the var_export($jsonData) output :


array (
  'result' => 'success',
  'invoiceid' => '228567',
  'invoicenum' => '',
  'userid' => '19577',
  'date' => '2017-05-18',
  'duedate' => '2017-07-10',
  'datepaid' => '2017-05-18 11:49:10',
  'lastcaptureattempt' => '0000-00-00 00:00:00',
  'subtotal' => '139.90',
  'credit' => '0.00',
  'tax' => '8.39',
  'tax2' => '0.00',
  'total' => '148.29',
  'balance' => '0.00',
  'taxrate' => '6.00',
  'taxrate2' => '0.00',
  'status' => 'Paid',
  'paymentmethod' => 'banktransfer',
  'notes' => '*price promotion renew mynic',
  'ccgateway' => false,
  'items' => 
  array (
    'item' => 
    array (
      0 => 
      array (
        'id' => '284674',
        'type' => 'Hosting',
        'relid' => '23014',
        'description' => 'Linux-Standard-Plan - adamzpest.com.my (10/07/2017 - 10/07/2018)160.00',
        'amount' => '80.00',
        'taxed' => '1',
      ),
      1 => 
      array (
        'id' => '284675',
        'type' => 'Domain',
        'relid' => '34730',
        'description' => 'Domain Renewal - adamzpest.com.my - 1 Year/s (10/07/2017 - 10/07/2018)',
        'amount' => '59.90',
        'taxed' => '1',
      ),
    ),
  ),
  'transactions' => 
  array (
    'transaction' => 
    array (
      0 => 
      array (
        'id' => '158331',
        'userid' => '19577',
        'currency' => '0',
        'gateway' => 'banktransfer',
        'date' => '2017-05-18 11:49:10',
        'description' => 'Invoice Payment',
        'amountin' => '148.29',
        'fees' => '0.00',
        'amountout' => '0.00',
        'rate' => '1.00000',
        'transid' => 'XEV-217-87171',
        'invoiceid' => '228567',
        'refundid' => '0',
      ),
    ),
  ),
)

Open in new window



Thank you.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Maybe we can try one other thing... Can you please post the JSON string.  I think that's the value in the $xml variable.  If we can process that with object-oriented notation it might be easier.
Here's a start...
https://iconoun.com/demo/temp_smksa.php
<?php // demo/temp_smksa.php
/**
 * https://www.experts-exchange.com/questions/29024306/How-to-convert-PHP-array-into-string.html#a42145306
 */
error_reporting(E_ALL);

// MAKE SURE THAT PHP WORKS WITH UTF-8
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

$aVarToExtract = [ 'invoiceid', 'invoicedate', 'credit', 'tax', 'total', 'balance', 'status', 'items' ];

$arr =
array (
  'result' => 'success',
  'invoiceid' => '228567',
  'invoicenum' => '',
  'userid' => '19577',
  'date' => '2017-05-18',
  'duedate' => '2017-07-10',
  'datepaid' => '2017-05-18 11:49:10',
  'lastcaptureattempt' => '0000-00-00 00:00:00',
  'subtotal' => '139.90',
  'credit' => '0.00',
  'tax' => '8.39',
  'tax2' => '0.00',
  'total' => '148.29',
  'balance' => '0.00',
  'taxrate' => '6.00',
  'taxrate2' => '0.00',
  'status' => 'Paid',
  'paymentmethod' => 'banktransfer',
  'notes' => '*price promotion renew mynic',
  'ccgateway' => false,
  'items' =>
  array (
    'item' =>
    array (
      0 =>
      array (
        'id' => '284674',
        'type' => 'Hosting',
        'relid' => '23014',
        'description' => 'Linux-Standard-Plan - adamzpest.com.my (10/07/2017 - 10/07/2018)160.00',
        'amount' => '80.00',
        'taxed' => '1',
      ),
      1 =>
      array (
        'id' => '284675',
        'type' => 'Domain',
        'relid' => '34730',
        'description' => 'Domain Renewal - adamzpest.com.my - 1 Year/s (10/07/2017 - 10/07/2018)',
        'amount' => '59.90',
        'taxed' => '1',
      ),
    ),
  ),
  'transactions' =>
  array (
    'transaction' =>
    array (
      0 =>
      array (
        'id' => '158331',
        'userid' => '19577',
        'currency' => '0',
        'gateway' => 'banktransfer',
        'date' => '2017-05-18 11:49:10',
        'description' => 'Invoice Payment',
        'amountin' => '148.29',
        'fees' => '0.00',
        'amountout' => '0.00',
        'rate' => '1.00000',
        'transid' => 'XEV-217-87171',
        'invoiceid' => '228567',
        'refundid' => '0',
      ),
    ),
  ),
)
;

foreach ($arr as $key => $val)
{
    if (in_array($key, $aVarToExtract))
    {
        echo PHP_EOL . "<b>$key: </b>";
        print_r($val);
        echo PHP_EOL;
    }
}

Open in new window

outputs something like:
<b>invoiceid: </b>228567

<b>credit: </b>0.00

<b>tax: </b>8.39

<b>total: </b>148.29

<b>balance: </b>0.00

<b>status: </b>Paid

<b>items: </b>Array
(
    [item] => Array
        (
            [0] => Array
                (
                    [id] => 284674
                    [type] => Hosting
                    [relid] => 23014
                    [description] => Linux-Standard-Plan - adamzpest.com.my (10/07/2017 - 10/07/2018)160.00
                    [amount] => 80.00
                    [taxed] => 1
                )

            [1] => Array
                (
                    [id] => 284675
                    [type] => Domain
                    [relid] => 34730
                    [description] => Domain Renewal - adamzpest.com.my - 1 Year/s (10/07/2017 - 10/07/2018)
                    [amount] => 59.90
                    [taxed] => 1
                )

        )

)

Open in new window

@Ray we have the data in JSON and PHP array format - not sure what else we need here. The question is about how to access that data - extracting it into more variables does not make sense - as you have correctly pointed out in many other threads.

The data is in $jsonData - to extract it is a case of simply accessing the array items.

In the case of the author's code he made some fundamental mistakes

1. He referred to elements of the array without referencing them properly
$status and $invoicedate are cases in point

2. He was confused about how to iterate over the items array - which is a confusing structure because it is an array with an array containing an element 'item' which is an array of item properties. Unpacking this is ambiguous because there is only one item - we don't know what an invoice with 2 or more items looks like - so a bit of guessing required there

He also tries to do something with the keys of the array - the intentions of which are unclear as the key is not really relevant.

The code I posted above addresses all of the above using the data the author supplied in his OP.
Thank you for both of you for helping me, both advice from you guys make my script works.
You are welcome