My php gives "null" while it is something [duplicate] - php

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 5 years ago.
So, I want to make my site check the bitcoin prices. I do that with virwox. So, I send a curl to http://api.virwox.com/api/json.php?method=getBestPrices&symbols[0]=BTC/SLL.
That gives me this:
{"result":[{"symbol":"BTC\/SLL","errorCode":"OK","bestBuyPrice":"983021","bestSellPrice":"1009989"}],"error":null,"id":""}
Now, I want the bestBuyPrice. So, I runned a json_decode on my $output. Then my $output is an array. So, I did json_encode("$output["result"]") to see what will come out of that. It gave me this:
[{"symbol":"BTC\/SLL","errorCode":"OK","bestBuyPrice":"983021","bestSellPrice":"1009989"}]
So, I tought if I do json_decode("$output["bestBuyPrice"]") I would get it, but I didn't. What I got was: null. How can I fix this?
Here is my full code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.virwox.com/api/json.php?method=getBestPrices&symbols[0]=BTC/SLL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$decode = json_decode($output, true);
$encode = json_encode($decode["result"]["bestBuyPrice"], true);
echo $encode; // Gives null
$koop = $decode["result"]["bestBuyPrice"]; // No result
$verkoop = $decode["result"]["bestSellPrice"]; // No result
echo $koop . "<br />".$verkoop;
?>
Thanks!

This one's real easy. Get rid of the quotes from around your variable!
json_encode("$output["result"]")
to
json_encode($output["result"])
EDIT:
Based on the var_dump in the comment below, it looks like there is another array key you need:
$koop = $decode["result"][0]["bestBuyPrice"];
Give that a try!

Related

Passing a PHP Variable to curl_init [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 2 years ago.
The following PHP code is working fine passing a specific IP Address to curl_init:
$ch = curl_init('https://ipgeolocation.abstractapi.com/v1/?api_key=my_key&ip_address=5.79.66.162');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$yummy = json_decode($data);
$country= $yummy->country; //this is working fine. country is being passed
===========================================
But I need to pass the ip address in a variable in the curl_init. However you cannot pass a PHP variable between single quotes. So the following curl_init statement is NOT working.
$ip="5.79.66.162";
$ch = curl_init('https://ipgeolocation.abstractapi.com/v1/?api_key=my_key&ip_address=$ip');
How does the code above = need to be changed in order for the call to work using a variable?
I would appreciate any help anyone can offer.
However you cannot pass a PHP variable between single quotes
Exactly, so you can use doble quotes here or string concatenation:
$ip="5.79.66.162";
$ch = curl_init("https://ipgeolocation.abstractapi.com/v1/?api_key=my_key&ip_address=$ip");
or
$ip="5.79.66.162";
$ch = curl_init('https://ipgeolocation.abstractapi.com/v1/?api_key=my_key&ip_address=' . $ip);

PHP Update with Curl Please

I am trying to update my API with an update curl function but am struggling to work out why it isn't working
The areas where it may be wrong is key($id) I want it to
extract the ID column based on the key value for the ID array.
$URL I want to create the URL based on the const variables plus the resource name plus the value of the ID array that has been passed through rawurlencode.
So far this is my update code, but am wondering what area is wrong.
I can provide more info if needed and appreciate any help, thanks
<?php
function update(array $id,array $vaules, $resourcename)
$jsonData = json_encode($vaules);
key($id);
$url = DOMAIN.FOLDER.APIPATH.$resourcename.rawurlencode("/".$id);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array ('content-type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,PUT);
curl_setopt($ch,CURLOPT_POSTFIELDS,$jsonData);
curl_exec($ch);
curl_getinfo(CURLINFO_HTTP_CODE);
}
The function key() returns the current key in an array (according to the internet pointer). Right now you're not doing anything with it, you're calling the function and not assigning it anywhere.
Did you mean to write: rawurlencode("/".key($id).$vaules);?
As your code is right now, assuming $id is an array, you're trying to convert an array into a string, which I doubt is what you want.

PHP cURL same HTML element [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 8 years ago.
I want to output the third element from the same HTML element. I know how to output a div or span with an id or a class but I have no idea how to output a same HTML element. I thought it was something with p[1] but it doesn't work.
I know there is a lot of answered questions about it but it never explained how to output the same HTML element without a class or id.
website : http://localhost/
<p>example</p>
<p>example1</p> <!-- i want to take this one -->
<p>example2</p>
-------------------
php script :
<?php $curl = curl_init('http://localhost/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$code3 = curl_exec($curl);
curl_close($curl);
$code = '/<p>(.*?)<\/p>/s';
$code6= preg_match($code, $code3, $code4);
echo $code4[1]
?>
/* doesn't work ..
also php.net doesnt give a good example about it so i hope someone can help me here.
thanks advanced !
*/
Try:
<?php
$curl = curl_init('http://justpaste.it/8s5v');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($curl);
curl_close($curl);
preg_match_all('/<p>(.+)<\/p>/im', $content, $result);
print_r($result);
print "Selected: " . $result[0][1] . "\n";
?>

Json_Decode not Decoding my JSON

I am using couchDB to get a UUID so that I can send a new document to the database.
In order to get this UUID, I use a curl statement:
function getUUID(){
$myCurlSubmit = curl_init();
curl_setopt($myCurlSubmit, CURLOPT_URL, 'http://localhost:5984/_uuids');
curl_setopt($myCurlSubmit, CURLOPT_HEADER, 0);
$response = curl_exec($myCurlSubmit);
curl_close($myCurlSubmit);
return $response;
}
This returns the expected result:
{"uuids":["af09ffd3cf4b35c2d94d1ed755000fb8"]}
However, the following json_decode fails:
print_r('No match, creating new document.');
$uuid = json_decode(trim(getUUID()));
var_dump(json_last_error());
The error printed is: 'int(0)' (not in quotes.), and $uuid is a json string still.
Help appreciated Thank you!
EDIT:
var_dump($uuid) = int(1)
EDIT:
var_dump(getUUID()) = {"uuids":["af09ffd3cf4b35c2d94d1ed755000fb8"]}\n1
Is there any reason why I would have a trailing one, and /n on my json??
EDIT:
The problem was with curl, look at the answer below!
The problem lies in the use of curl in the getUUID() function.
You must set CURLOPT_RETURNTRANSFER, otherwise curl_exec will just echo the result, while returning 1 (as you see).
See for example this comment in the curl_exec manual: http://www.php.net/manual/de/function.curl-exec.php#13020

website query, php

How can I query a particular website with some fields and get the results to my webpage using php?
let say website xyz.com will give you the name of the city if you give them the zipcode. How can I acehive this easliy in php? any code snap shot will be great.
If I understand what you mean (You want to submit a query to a site and get the result back for processing and such?), you can use cURL.
Here is an example:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "example.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
?>
You can grab the Lat/Long from this site with some regexp like this:
if ( preg_match_all( "#<td>\s+-?(\d+\.\d+)\s+</td>#", $output, $coords ) ) {
list( $lat, $long ) = $coords[1];
echo "Latitude: $lat\nLongitude: $long\n";
}
Just put that after the curl_close() function.
That will return something like this (numbers changed):
Latitude: 53.5100
Longitude: 60.2200
You can use file_get_contents (and other similar fopen-class functions) to do this:
$result = file_get_contents("http://other-site.com/query?variable=value");
Do you mean something like:
include 'http://www.google.com?q=myquery'; ? or which fields do you want to get?
Can you be a bit more specific pls :)
If you want to import the html to your page and analyze it, you probably want to use cURL.
You have to have the extensions loaded to your page (it's usually part of PHP _ I think it has to be compiled in? The manual can answer that)
Here is a curl function. Set up your url like
$param='fribby';
$param2='snips';
$url="www.example.com?data=$param&data2=$param2";
function curl_page($url)
{
$response =false;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_FAILONERROR,true);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$page_data=curl_page($url);
Then, you can get data out of the page using the DOM parsing or grep/sed/awk type stuff.

Categories