implode an array with "," [duplicate] - php

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I call the Proxmox API to get the names of the vm in each node. This part of code works well (more complete part of my code at the end of this post) :
foreach ($arrays['data'] as $array) {
echo $array['name'];
}
echo : vm1vm2vm3.
But I would like to see this result, separated by commas : vm1, vm2, vm3.
I tried :
foreach ($arrays['data'] as $array) {
echo implode(',', $array['name']);
}
But error : "Warning: implode(): Invalid arguments passed in"
So I tried with :
foreach ($arrays['data'] as $array) {
echo implode(',', (array)$array['name']);
}
No error but no comma. Same result as simple "echo $array['name'];"
And finally I tried :
foreach ($arrays['data'] as $array) {
$vmNameWithComma[] = $array['name'];
echo implode(',', $vmNameWithComma);
}
which returns : vm1vm1,vm2vm1,vm2,vm3.
Any idea ?
foreach ($servers as $server) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://'.$onlinenode.'/api2/json/nodes/'.$server['node'].'/qemu');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Cookie: PVEAuthCookie=' . $cookie;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'La machine ' .$server['node']. ' est injoignable (erreur : ' . curl_error($ch) . ').<br>';
}
else {
$arrays = json_decode($result, true);
$vmcount = count((array) $arrays['data']);
if ($vmcount == 0) {
echo 'Server ' .$server['node']. ' doesn\'t host vm.<br>';
}
else if ($vmcount == 1) {
echo 'Server ' .$server['node']. ' host only one vm which is : ' .$arrays['data']['0']['name']. '<br>';
}
else {
echo 'Server ' .$server['node']. ' host' .$vmcount. ' vm which are : ';
foreach ($arrays['data'] as $array) {
$vmNameWithComma[] = $array['name'];
echo implode(',', $vmNameWithComma);
}
echo '.<br>';
}
}
curl_close($ch);
}

You don't need the foreach loop.
You need to make an array of just the name columns, then call implode() on that.
$names = array_column($arrays['data'], 'name');
echo implode(',', $names);

Related

PHP List items in json data in a table

I am doing some requests using php i am getting this json data from the url i am requesting from and i need to list the name and tag category of each different set of brackets or item out in html how would i go about this see my code below
<?php
$query = $_POST['query'];
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"https://api.spiget.org/v2/search/resources/" + $query);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$json = json_decode($result);
foreach ($json['items'] as $data)
{
echo "<h3>". $json['name']."</h3>";
echo "<h4>". $json['tag']."</h3>";
echo "\n";
echo "\n";
echo "\n";
};?>
JSON DATA
Warning: A non-numeric value encountered in C:\xampp\htdocs\request.php on line 7
Warning: A non-numeric value encountered in C:\xampp\htdocs\request.php on line 7
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\request.php on line 14
Those are the errors i get when the file is run
You define in your json loop as $data so you need to use it in displaying
<?php
$query = $_POST['query'];
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"https://api.spiget.org/v2/search/resources/" + $query);
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$json = json_decode($result);
foreach ($json['items'] as $data)
{
echo "<h3>". $data['name']."</h3>";
echo "<h4>". $data['tag']."</h3>";
echo "\n";
echo "\n";
echo "\n";
};?>

Issues with decoding two JSON feed sources and display with PHP/HTML

I am using two JSON feed sources and PHP to display a real estate property slideshow with agents on a website. The code was working prior to the feed provider making changes to where they store property and agent images. I have made the necessary adjustments for the images, but the feed data is not working now. I have contacted the feed providers about the issue, but they say the problem is on my end. No changes beyond the image URLs were made, so I am unsure where the issue may be. I am new to JSON, so I might be missing something. I have included the full script below. Here are the two JSON feed URLs: http://century21.ca/FeaturedDataHandler.c?DataType=4&EntityType=2&EntityID=2119 and http://century21.ca/FeaturedDataHandler.c?DataType=3&AgentID=27830&RotationType=1. The first URL grabs all of the agents and the second grabs a single agent's properties. The AgentID value is sourced from the JSON feed URL dynamically.
class Core
{
private $base_url;
private $property_image_url;
private $agent_id;
private $request_agent_properties_url;
private $request_all_agents_url;
private function formatJSON($json)
{
$from = array('Props:', 'Success:', 'Address:', ',Price:', 'PicTicks:', ',Image:', 'Link:', 'MissingImage:', 'ShowingCount:', 'ShowcaseHD:', 'ListingStatusCode:', 'Bedrooms:', 'Bathrooms:', 'IsSold:', 'ShowSoldPrice:', 'SqFootage:', 'YearBuilt:', 'Style:', 'PriceTypeDesc:');
$to = array('"Props":', '"Success":', '"Address":', ',"Price":', '"PicTicks":', ',"Image":', '"Link":', '"MissingImage":', '"ShowingCount":', '"ShowcaseHD":', '"ListingStatusCode":', '"Bedrooms":', '"Bathrooms":', '"IsSold":', '"ShowSoldPrice":', '"SqFootage":', '"YearBuilt":', '"Style":', '"PriceTypeDesc":' );
return str_ireplace($from, $to, $json); //returns the clean JSON
}
function __construct($agent=false)
{
$this->base_url = 'http://www.century21.ca';
$this->property_image_url = 'http://images.century21.ca';
$this->agent_id = ($agent ? $agent : false);
$this->request_all_agents_url =
$this->base_url.'/FeaturedDataHandler.c?DataType=4&EntityType=3&EntityID=3454';
$this->request_agent_properties_url =
$this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$this->agent_id.'&RotationType=1';
}
/**
* getSlides()
*/
function getSlides()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->request_all_agents_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
if (empty($response))
return false;
else
$agents = $this->decode_json_string($response);
// Loop Agents And Look For Requested ID
foreach ($agents as $agent)
{
if (($this->agent_id != false) && (isset($agent['WTLUserID'])) && ($agent['WTLUserID'] != $this->agent_id))
{
continue; // You have specified a
}
$properties = $this->getProperties($agent['WTLUserID']);
$this->print_property_details($properties, $agent);
}
}
/**
* getProperties()
*/
function getProperties($agent_id)
{
$url = $this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$agent_id.'&RotationType=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response);
if (empty($response))
die('No response 2'); //return false;
else
$json = $this->formatJSON($this->decode_json_string($response));
var_dump($json);
die();
// return $json;
}
/**
* print_property_details()
*/
function print_property_details($properties, $agent, $html='')
{
$BASE_URL = $this->base_url;
$PROPERTY_IMAGE_URL = $this->property_image_url;
foreach ($properties as $property)
{
$img = $property['Image'];
// $img = ($property['Image'] ? $property['Image'] : "some url to a dummy image here")
if($property['ListingStatusCode'] != 'SOLD'){
$address = $property['Address'];
$shortaddr = substr($address, 0, -12);
$html .= "<div class='listings'>";
$html .= "<div class='property-image'>";
$html .= "<img src='". $PROPERTY_IMAGE_URL ."' width='449' height='337' alt='' />";
$html .= "</div>";
$html .= "<div class='property-info'>";
$html .= "<span class='property-price'>". $property['Price'] ."</span>";
$html .= "<span class='property-street'>". $shortaddr ."</span>";
$html .= "</div>";
$html .= "<div class='agency'>";
$html .= "<div class='agent'>";
$html .= "<img src='". $agent['PhotoUrl']. "' class='agent-image' width='320' height='240' />";
$html .= "<span class='agent-name'><b>Agent:</b>". $agent['DisplayName'] ."</span>";
$html .= "</div>";
$html .= "</div>";
$html .= "</div>";
}
}
echo $html;
}
function decode_json_string($json)
{
// Strip out junk
$strip = array("{\"Agents\": [","{Props: ",",Success:true}",",\"Success\":true","\r","\n","[{","}]");
$json = str_replace($strip,"",$json);
// Instantiate array
$json_array = array();
foreach (explode("},{",$json) as $row)
{
/// Remove commas and colons between quotes
if (preg_match_all('/"([^\\"]+)"/', $row, $match)) {
foreach ($match as $m)
{
$row = str_replace($m,str_replace(",","|comma|",$m),$row);
$row = str_replace($m,str_replace(":","|colon|",$m),$row);
}
}
// Instantiate / clear array
$array = array();
foreach (explode(',',$row) as $pair)
{
$var = explode(":",$pair);
// Add commas and colons back
$val = str_replace("|colon|",":",$var[1]);
$val = str_replace("|comma|",",",$val);
$val = trim($val,'"');
$val = trim($val);
$key = trim($var[0]);
$key = trim($key,'{');
$key = trim($key,'}');
$array[$key] = $val;
}
// Add to array
$json_array[] = $array;
}
return $json_array;
}
}
Try this code to fix the JSON:
$url = 'http://century21.ca/FeaturedDataHandler.c?DataType=3&AgentID=27830&RotationType=1';
$invalid_json = file_get_contents($url);
$json = preg_replace("/([{,])([a-zA-Z][^: ]+):/", "$1\"$2\":", $invalid_json);
var_dump($json);
All your keys need to be double-quoted
JSON on the second URL is not a valid JSON, that's why you're not getting the reults, as PHP unable to decode that feed.
I tried to process it, and get this error
Error: Parse error on line 1:
{Props: [{Address:"28
-^
Expecting 'STRING', '}'
Feed image for first URL
and here is view of 2nd URL's feed
as per error for second feed, all the keys should be wrapped within " as these are strings rather than CONSTANTS.
e.g.
Props should be "Props" and all other too.
EDIT
You need to update your functionand add this one(formatJSON($json)) to your class
// Update this function, just need to update last line of function
function getProperties($agent_id)
{
$url = $this->base_url.'/FeaturedDataHandler.c?DataType=3'.'&AgentID='.$agent_id.'&RotationType=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$json = json_decode($response);
if (empty($response))
die('No response 2'); //return false;
else
return $this->formatJSON($this->decode_json_string($response)); //this one only need to be updated.
}
//add this function to class. This will format json
private function formatJSON($json){
$from= array('Props:', 'Success:', 'Address:', ',Price:', 'PicTicks:', ',Image:', 'Link:', 'MissingImage:', 'ShowingCount:', 'ShowcaseHD:', 'ListingStatusCode:', 'Bedrooms:', 'Bathrooms:', 'IsSold:', 'ShowSoldPrice:', 'SqFootage:', 'YearBuilt:', 'Style:', 'PriceTypeDesc:');
$to = array('"Props":', '"Success":', '"Address":', ',"Price":', '"PicTicks":', ',"Image":', '"Link":', '"MissingImage":', '"ShowingCount":', '"ShowcaseHD":', '"ListingStatusCode":', '"Bedrooms":', '"Bathrooms":', '"IsSold":', '"ShowSoldPrice":', '"SqFootage":', '"YearBuilt":', '"Style":', '"PriceTypeDesc":' );
return str_ireplace($from, $to, $json); //returns the clean JSON
}
EDIT
I've tested that function, and it's working fine, may be there is something wrong with your function decode_json_string($json)
I've taken unclean json from second URL, and cleaning it here, and putting that cleaned json in json editor to check either it's working or not HERE

php foreach loop with 2 variables in json_decode

In a foreach loop i am trying to make a link with data from two variables. Like this:
$baseAttachementUrl = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);
foreach ($attachments as $attachment){
$rowAttachTags = array('{{ROWID}}', '{{SHEETID}}','{{ATTACHMENTID}}');
$rowAttachVals = array($addRowsObj->result[0]->id, $theSheet->id, $attachment->id);
$getAttachmentURL = $baseAttachementUrl;
$getNEWAttachmentURL = str_replace($rowAttachTags, $rowAttachVals, $getAttachmentURL);
$curlSession = curl_init($getNEWAttachmentURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
getAttachmentResponse = curl_exec($curlSession);
$getFileObj = array(json_decode($getAttachmentResponse, true));
foreach ($getFileObj as $fileObj){
echo "<a href='". $fileObj['url']."'>". $fileObj['name']."</br></a>";
}
}
The first row in the table works. 2 files comes out with the right url. but in all subsequent rows the last file from the first row comes out.
A couple of problems here that you are not being too specific about. However I will try my best to respond.
First of all, we dont know how the results of $attachments or $getFileObj look like. We are assuming that the part of your question that says "returns stdClas..." is a portion of the results of $getFileObj.
Another problem is that we dont know where you're getting $getAttachmentURL from.. Is this a variable statically set, or is it a variable that comes as a result of $attachments?
Taking those problems into consideration I believe what you're trying to do is to first get the all the attachments and store them into $attachments. Then, you want to get each attachment url from you intial result and iterate through each to get your fileURL. I would do the following:
<?php
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getAttachmentsResponse = curl_exec($curlSession);
// Assign response to variable
$attachments = json_decode($getAttachmentsResponse);
foreach ($attachments as $attachment) {
$getAttachmentURL = $attachment->attachment_URL;
$curlSession = curl_init($getAttachmentURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getAttachmentResponse = curl_exec($curlSession);
// Assign response to variable
$getFileObj = json_decode($getAttachmentResponse);
echo "<td>";
echo "<a href='" . $getFileObj->url . "'>" . $attachment->name . "</br></a>";
echo "</td>";
}
Try....
// ... curl setup
$attach = json_decode($getAttachmentsResponse);
// ... curl setup two
$file = json_decode($getAttachmentResponse);
$joinedattachment[ 'attach' ] = $attachone;
$joinedattachment[ 'file' ] = $file;
$attachments[] = $joinedattachment;
$iCountAttachments = count( $attachments );
echo "<td>";
for( $i = 0; $i < $iCountAttachments; ++$i )
{
echo "<a href='". $attachments[ $i ][ 'file' ]."'>". $attachments[ $i ][ 'attach' ] ."</br></a>";
}
echo "</td>";

http_build_query () cannot retrieve the desired query, PHP

I'm working on Bing Search API:
Here's the code:
<?php
if (isset($_GET['keyword'])) {
$keyword = $_GET['keyword'];
} else {
echo 'Wrong!';
}
$key = 'NNNNN'; //key for API
$root = 'https://api.datamarket.azure.com/Bing/Search/';
$search = $root . 'Web?$format=json&Query=';
$req = $search . '\'' . $keyword . '\'';
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $key . ":" . $key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($ch);
$json = json_decode($resp);
foreach ($json->d->results as $item) {
$rss_item = array(
'Title' => $item->Title,
'Description' => $item->Description,
'DisplayUrl' => $item->DisplayUrl,
'Url' => $item->Url,
);
array_push($desArray, $item->Description);
array_push($rss_array, $rss_item);
}
for ($i = 0; $i < 50; $i++) {
echo '<p class="bagi">' . '' . $rss_array[$i]['Title'] . '
' . '<img src="'.base_url().'TAMPILAN/images/open_new_tab.jpg" width="10px" height="10px" title="Open in new tab">
<br/>' .
$rss_array [$i]['Description'] . '</br>' .
'<hr/>' .
'</p>';
}
?>
I typed on my browser with:
http://localhost/MSP/SignIn/cariBing.php?keyword=statistics
But it gave me the list of the search results 50 items, complete no error, but when I used:
http://localhost/MSP/SignIn/cariBing.php?keyword=statistical+terms
It gave me Trying to get property of non-object, undefined offset, repeatedly. Then I realised the problem was on the query (keyword). The code couldn't handle such keyword that had space in it. So I tried this:
if (isset($_GET['keyword'])) {
$queryString = array();
foreach ($_GET as $keyword => $value) {
$queryString[] = $keyword .'='. $value;
}
$queryString = http_build_query($queryString, $keyword);
} else {
echo 'Wrong!';
}
I tested it with the http://localhost/MSP/SignIn/cariBing.php?keyword=statistical+terms
It gave me the results, but the results refers to a query "keyword", not "statistical terms" as I wanted, or whatever I typed.
Where did I miss? Thanks very much in advance.
I think you mean
$queryString = http_build_query(array("keyword"=>$_GET["keyword"]));
or if you want all of the $_GET parameters
$queryString = http_build_query($_GET);
replacement for your last code snippet should be
if (isset($_GET['keyword'])) {
$queryString = http_build_query($_GET);
} else {
echo 'Wrong!';
}

why $items is Null

I have this line in my code:
$item=$page->items;
$page is an array, and its content is as it should be but $item is Null. do you have any idea what could be the reason?
UPDATE:
<?php
search( "Steve Jobs" );
// Submit query to Google Web Search
function search( $query )
{
$url = "https://www.googleapis.com/customsearch/v1?key=YOUR_KEY&cx=YOUR_SEARCHE_NGINE_ID&q=" . urlencode( $query ) . "&callback=handleResponse&prettyprint=true&num=10";
$result = get_web_page( $url );
// Exception handling
if ( $result['http_code'] == 403 )
echo "... error: daily limit exceeded ...";
if ( $result['errno'] != 0 )
echo "... error: bad url, timeout, redirect loop ...";
if ( $result['http_code'] != 200 )
echo "... error: no page, no permissions, no service ...";
// Get and parse JSON output
$page = $result['content'];
$page = str_replace("// API callback\nhandleResponse(", "", $page);
$page = str_replace(");", "", $page);
$page=json_decode($page, true);
// Print results
$items=$page->items;
var_dump($items);
for ($i = 0; $i < sizeof($items); $i++)
{
$item = $items[$i];
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
}
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
?>
ANSWER:
this part should be changed since $page is an array.
$items = $page['items'];
foreach ($items as $item)
{
$item = (object) $item;
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
Simple question, simple answer:
$item is NULL because $page->items is NULL.
More details:
You're treating $page as an object, but you write it's an array.
Suggestion:
Treat $page as an array instead.
Further information:
The PHP manual has information how to treat a value like an array or like an object. Additionally if you enable warnings on your development box, you will be notified about undefined properties which are always NULL.
Update:
For your concrete code, with a slight modification this should work, just change your for loop a bit:
foreach ($items as $item)
{
$item = (object) $item;
print("<font size=\"3\">" . "" . $item->htmlTitle . "</font><br>");
print("<font size=\"2\" color=\"black\">" . $item->htmlSnippet . "</font><br>");
print("<font size=\"2\" color=\"green\">" . $item->displayLink . "</font><br>"); print("<br>");
}
$page is an array, and its content is as it should be
If $page is an array, you should access it like
$item=$page['items'];
If you provide more info you would get more helpful answer.
EDIT
First, Please make sure you have $page not empty at all.
What you have is $page=json_decode($page, true); that return an associative array and you should use the way I posted above.
If you don't want the array to be returned you should change your json_decode to return object by not passing second argument as true.
$page=json_decode($page); then you are okay with the code you have right now.
If $page is array you do this $page['items']. If it is JSON or XML you can also access ait the way you are doing. like $page->items;

Categories