Having trouble loading php curl results - php

So I'm having a problem with the following code.
I've got CURLOPT_RETURNTRANSFER set to true, yet nothing is returned when curl_exec is hit. Any and all help is appreciated!
<?php
$yql_base_url = "http://query.yahooapis.com/v1/public/yql?q=";
$yql_query = "select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=YHOO,GOOG,AAPL&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'";
$yql_params = "&format=json&diagnostics=true&callback=";
$yql_url = $yql_base_url . urlencode($yql_query) . $yql_params;
$session = curl_init($yql_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($session);
curl_close($session);
$phpObj = json_decode($json);
if(!is_null($phpObj->query->results))
{
echo $phpObj->query->results;
}
?>

$phpObj->query->results is an array of Object and you can not do echo on it. Simply use print_r() or var_dump() on it.
Example:
print_r($phpObj->query->results);
var_dump($phpObj->query->results);

Related

How to print an array element from JSON into PHP

If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
$obj = json_decode($json_str);
echo "id: $obj->id<br>";
?>
</body>
</html>
All I want is receive the MLB752465575 part into my browser.
How can I do it?
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
echo "error " . $httpcode;
curl_close($ch);
return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);
$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);
echo "id: {$obj->id}<br>";
What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.

Catchable fatal error: Object of class stdClass could not be converted to string / No return

The problem is that $price return nothing.
I'm using https://github.com/PHPGangsta/GoogleAuthenticator for the TOTP part of the code.
I have tried to play around with settype() for the $price, but seems like it doesn't really work.
If I change $obj->data->prices[0]->price to $obj->data. I get this error
Catchable fatal error: Object of class stdClass could not be converted to string in
<?php
$secret ="(Verify Secret)";
$api = "(API Key)";
require_once 'GoogleAuthenticator.php';
$ga = new PHPGangsta_GoogleAuthenticator();
$oneCode = $ga->getCode($secret);
$itemName=str_replace(array(' ','"','\'','\\\'','\\'),array('%20',null,null,null,null),$_GET['name']);
$url = "https://bitskins.com/api/v1/get_item_price/?api_key=" . $api . "&code=" . $oneCode . "&names=" . $itemName . "&delimiter=!END!";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$obj = curl_exec($curl);
$obj = json_decode(curl_exec($curl));
curl_close($curl);
$price = $obj->data->prices[0]->price;
echo "Price: ".$price."<br>";
echo "itemName: ".$itemName."<br>";
echo "url: ".$url;
?>
What kind of debugging have you done? Have you done a var_dump() for each var you've declared to see what gets returned?
I looked at the bitskins api, and I don't see "get_item_price" as an option.
Are you sure that you don't mean to use get_price_data_for_items_on_sale?
Well, this is kind of embarrassing as the problem is that I disabled API access shortly and forgot to turn it on again.

Get location from a stream url in PHP

I'm trying to get the redirect url from a stream using php.
Here's the code I have right now:
<?php
$stream = 'https://api.soundcloud.com/tracks/178525956/stream?client_id=XXXXXX';
$ch = curl_init($stream);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$url = curl_exec($ch);
echo $url;
curl_close($ch);
?>
Which outputs as a string:
{"status":"302 - Found","location":"THE_URL_I_WANT"}
So how ould I go about getting the url I want as a variable?
Thanks
It's simple use json_decode
$data = json_decode($url);
$your_url = $data->location;
How about
$data = json_decode($url);
$location = $data["location"];

PHP curl_setopt : Variable Not working in place of URL string

I use CURL in php, and I use CURL something like this
$url = "http://exampledomain.com";
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
This is not working, but if I wrote "http://exampledomain.com" in place of "$smsURL" at curl_setopt (); It will work fine. Where is issue in my code? did I miss something?
Original Code
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . $_POST['txt_customer_contact_no'];
$url .= '&sender=' . strtoupper($saloon_info['saloon_name']);
$url .= '&is_payor=' . $this->conf['sms_is_payor'];
$url .= '&pay_amount=' . $this->conf['sms_pay_amount'];
$url .= '&token=5ce7467e9ec045cbbac448ba5a422a02';
//$url .= '&customer_num=' . $this->conf['sms_customer_num'] . $saloon_id;
$url .= '&customer_num=' . $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name']; //$value['id_employee'];
//$sms_msg = "Hey. Recalling that I await tomorrow at. " . $appointment_time . " Regards " . $employee_name . ", " . $saloon_name . ". ";
$sms_msg = t('msg_sms_book_appointment', array('%emp_name' => $employee_name, '%saloon_name' => $_POST['hdn_selected_saloon_name'], '%time' => $appointment_time));
$url .= '&sms_msg=' . $sms_msg;
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
Thanks
You compose the URL from pieces but you don't encode the values properly. There are characters that have special meaning in URLs (/, ?, &, =, %, , + and a few more). They have to be encoded when they appear in the values from the query string, in order to retain their literal meaning.
PHP helps you for this goal with function urlencode() that can be used to encode each value individually when you create a query string. Something like this:
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . urlencode($_POST['txt_customer_contact_no']);
$url .= '&sender=' . urlencode(strtoupper($saloon_info['saloon_name']));
...
But, because this is a tedious work, it also provides an easier method. Put all the values you need into an array, using the names of the variables as keys, then pass the array to function http_build_query(). There is no need to call urlencode() any more; http_build_query() takes care of it. Also it puts ampersands (&) between the variables and equals (=) where they belong.
The code is like this:
$url = $this->conf['sms_getway_url'];
// Prepare the values to put into the query string
$vars = array();
$vars['recipient'] = $_POST['txt_customer_contact_no'];
$vars['sender'] = strtoupper($saloon_info['saloon_name']);
$vars['is_payor'] = $this->conf['sms_is_payor'];
$vars['pay_amount'] = $this->conf['sms_pay_amount'];
$vars['token'] = '5ce7467e9ec045cbbac448ba5a422a02';
$vars['customer_num'] = $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name'];
$sms_msg = t('msg_sms_book_appointment', array(
'%emp_name' => $employee_name,
'%saloon_name' => $_POST['hdn_selected_saloon_name'],
'%time' => $appointment_time,
));
$vars['sms_msg'] = $sms_msg;
// Now, the magic comes into place
$smsURL = $url.'?'.http_build_query($vars);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
if (! curl_exec ($curl)) {
// Something went wrong. Check the status code (at least)
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Do something here.
// If $code >= 500 then the remote server encountered an internal error
// retry later or ask them to fix it
// If 400 <= $code < 500 then there is a problem with the request:
// maybe the resource is not there (404, 410)
// or you are not allowed to access it (403)
// or something else.
echo('Failure sending the SMS. HTTP status code is '.$code."\n");
}
curl_close ($curl);
Check the list of HTTP status codes for more details.

How could I get contents of simpleXML array object when I encode it into JSON?

I have a php function that fetches and returns tweets data from twitter as simplexml object.I could get its contents by using php syntax. Here is php function
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.atom?q=" . urlencode( $q ) . "&rpp=100";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//Raw xml
$result = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($result);
return $xml;
}
?>
If I call it like
$xml = searchResults('xyz');
I could fetch its contents like
echo $xml->content.''.$xml->author->name;
Now I need to return it from php function in JSON format. Like
return json_encode($xml);
in spite of
return $xml;
So how do now I get same 'content' and 'author->name' etc contents from it in JSON format when I decode json.
If you don't need the XML for any other reason than to return it as JSON, why not use json format as the response for the Twitter API call?
http://search.twitter.com/search.json?q=blablabla
This returns the response in a JSON string that you could just return.
I would rewrite your code like this:
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.json?q=" . urlencode( $q ) . "&rpp=100";
$raw_json = file_get_contents($host);
return $raw_json;
}
?>
It depends. If you're accessing it back from PHP, there are two ways:
$obj = json_decode($json);
echo $obj->author->name;
or
$arr = json_decode($json, true);
echo $arr['author']['name'];
If you are accessing it using JavaScript, it should be:
alert(jsObject.author.name);

Categories