Making a JSON call from PHP - php

Not sure why but I am not getting anything back from the json call. I echo'ed the content out and pasted to my url bar of my browser and it works. Is there some sort of domain problem here that I need to address?
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$json = file_get_contents($call);
print_r($json);
}
close_db($connect);

file_get_contents() may not always work for external URLs. From php.net:
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

So the echo-ing works? Thus, there is valid JSON? And now what is the problem? If you want JSON to an Array, then json_decode() is what you want.
See http://php.net/manual/en/function.json-decode.php for more info.

If You want to further process the data, You could do it like this:
$data = array();
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$data[] = json_decode(file_get_contents($call));
}
close_db($connect);
foreach($data as $d)
print_r($d);
With this data which should be an array of arrays You can then do whatever You want...
EDIT:
If file_get_contents() is not working, try this:
$data = array();
$connect = open_db();
$result = mysql_query("SELECT search_id, search_term FROM search WHERE search_poi_id IS NULL");
while($row = mysql_fetch_assoc($result)){
$call = "http://maps.google.com/maps/api/geocode/json?address=".$row["search_term"]."&sensor=false";
$handle = fopen($call, "rb");
$contents = stream_get_contents($handle);
fclose($handle);
$data[] = json_decode($contents);
}
close_db($connect);
foreach($data as $d)
print_r($d);

Related

How to assign SplFileObject::fpassthru output to variable

I'm currently writing some data to an SplFileObject like this:
$fileObj = new SplFileObject('php://text/plain,', "w+");
foreach($data as $row) {
$fileObj->fputcsv($row);
}
Now, I want to dump the whole output (string) to a variable.
I know that SplFileObject::fgets gets the output line by line (which requires a loop) but I want to get it in one go, ideally something like this:
$fileObj->rewind();
$output = $fileObj->fpassthru();
However, this does not work as it simply prints to standard output.
There's a solution for what I'm trying to achieve using stream_get_contents():
pass fpassthru contents to variable
However, that method requires you to have direct access to the file handle.
SplFileObject hides the file handle in a private property and therefore not accessible.
Is there anything else I can try?
After writing, do a rewind() then you can read everything. The example is for understanding:
$fileObj = new SplFileObject('php://memory', "w+");
$row = [1,2,'test']; //Test Data
$fileObj->fputcsv($row);
$fileObj->rewind();
//now Read
$rowCopy = $fileObj->fgetcsv();
var_dump($row == $rowCopy);//bool(true)
$fileObj->rewind();
$strLine = $fileObj->fgets(); //read as string
$expected = "1,2,test\n";
var_dump($strLine === $expected); //bool(true)
//several lines
$fileObj->rewind();
$fileObj->fputcsv(['test2',3,4]);
$fileObj->fputcsv(['test3',5,6]);
$fileObj->rewind();
for($content = ""; $row = $fileObj->fgets(); $content .= $row);
var_dump($content === "test2,3,4\ntest3,5,6\n"); //bool(true)
If you absolutely have to fetch your content with only one command then you can do this too
// :
$length = $fileObj->ftell();
$fileObj->rewind();
$content = $fileObj->fread($length);
getSize() doesn't work here.
In the absence of an inbuilt function I've decided to do php output buffering as #CBroe had suggested.
...
$fileObj->rewind();
ob_start();
$fileObj->fpassthru();
$buffer = ob_get_clean();
See #jsplit's answer for a better method using SplFileObjects inbuilt functions

PHP Array file_get_contents for each query

Using the following code:
<?php
$url = $_GET['name'];
$nurl = str_replace('%3B', ';', $url);
$arr = explode("=", $nurl);
$rValue = parse_url($nurl, PHP_URL_QUERY);
preg_match_all('/\w+=.*/',$rValue,$matches);
parse_str($matches[0][0], $output);
parse_str($rValue);
echo $rValue;
?>
I get the following output:
field1=6918795;6990788;21434586&person144453469&number1=7412127;11425470;31104141&person86762935&number2=9152334;26300968;26441141&person38579423&number3=7897334;9114514;11656368;13683203
The question:
How to get file get contents from an URL for each query?
Example:
File get contents for field1 (of which the number 1 is a variable)
File get contents for 6918795
File get contents for 6990788
File get contents for 21434586
File get contents for person144453469 (the number 144453469 is a variable)
etc.
$var = field1=6918795;6990788;21434586&person144453469&number1=7412127;11425470;31104141&person86762935&number2=9152334;26300968;26441141&person38579423&number3=7897334;9114514;11656368;13683203
First separate by &
$separated_by_ands = explode('&', $var) ;
foreach($separated_by_ands as $separated_by_and) {
$separated_by_equals = explode('=', $separated_by_and);
$separated_by_equals = $separated_by_equals[1];
$separated_by_semicolons = explode(';', $separated_by_equals);
foreach($separated_by_semicolons as $number) {
//do file get contents for $number
}
}
yes I know bad choice of variable names :P

Insert Mysql data into Json file doesn't work

I have a script that doesn't work I hope some developers of you know the solution.
<?php
//Create Database connection
$db = mysql_connect("localhost","d","d");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("d",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from events", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
$file = 'events.json';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
// Write the contents back to the file
file_put_contents($file, $json_response);
//Close the database connection
?>
But the events.json is empty? Does anyone know the solution?
first,
echo json_encode($json_response);
file_put_contents($file, $json_response);
this is not writing json you should do this
file_put_contents($file, json_encode($json_response));
maybe it's the issue, you can't write an array into a file.
second, are you missing some code ?
$current = file_get_contents($file);
// Append a new person to the file
we don't see the code to append here, your code just replaces the content by the array $json_response (and not a json encoded array).
You haven't stored the json encoded response anywhere. Below your echo statement, add the line:
$json_response = json_encode($json_response);
You write: // Append a new person to the file but never append, rather replaces the content of the file.
When you call file_put_contents($file, $json_response); you have not yet made $json_response into a json string.
Try change:
echo json_encode($json_response);
To:
$json_response = json_encode($json_response);
To correctly convert the data to a json-string.
To append the data to the file (now I'm going to assume that the file contains data formatted the same as the data you are trying to write), load it as you do with file_get_contents then convert the content to an associative array with: json_decode($dataFromFile, true); (the true flag as second argument makes the return value into an associative array, rather than an object) and merge the two lists, before writing it to file.
use this :
$json_response = json_encode($json_response);

Php JSON encoding gives result {"table":null}

I didn't work with json before. Im trying to generate a .json file from the data of my sql database.
$con=mysqli_connect(...);
$response = array();
$partik = array();
$result = mysqli_query($con,"SELECT * FROM partik");
while($row=mysqli_fetch_array($result))
{
$nev=$row['im'];
$leiras=$row['leiras'];
$kezdes=$row['kezdes'];
$hely=$row['hely'];
$partik[] = array('im'=> $nev, 'leiras'=> $leiras, 'kezdes'=> $kezdes, 'hely'=> $hely);
}
$response['partik'] = $partik;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
The sql connection works.
What is wrong in my code? I get a .json file, but with null value.
try this in your while
$row = mysql_fetch_array($result, MYSQL_ASSOC)
like that you will get an associatif array

saving MySQL query to two arrays

I'm sure this is simple for someone else, but it escapes me.
I have a function that generates a .csv file based on a query input from an internal website.
The problem is, for speed purposes, I want to run 1 query to save to two different arrays. One of which I can pass to a function, the other to use for printing a table.
I've tried to pass the same $result var to the function. It seems to strip the data once sent through function? I need some help.
code for function:
function save_to_csv($result1, $filename, $attachment = false, $headers = true) {
if($attachment) {
// send response headers to the browser
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
} else {
$fp = fopen($filename, 'w');
}
$result1 = mysql_query($query1) or die( mysql_error() );
if($headers) {
// output header row (if at least one row exists)
$row = mysql_fetch_assoc($result1);
if($row) {
fputcsv($fp, array_keys($row));
// reset pointer back to beginning
mysql_data_seek($result1, 0);
}
}
while($row = mysql_fetch_assoc($result1)) {
fputcsv($fp, $row);
}
fclose($fp);
}
I've tried setting second array like so
$csv_result = array();
also tried
$csv_result = $result = mysql_query($query);
I'm assuming it's something here, but I just cant see it.
There's nothing in this code that demonstrates why you need two separate arrays. After the line where you set $result1, you can simply do the following for the exact same effect:
$row = mysql_fetch_assoc($result1);
if ($row) {
if ($headers) {
fputcsv($fp, array_keys($row));
}
fputcsv($fp, $row);
}
The variable $row hasn't been modified, and is still equal to the data retrieved from $query1. There's really no need to make a duplicate array unless one of them is going to be modified. However, if you want to make a copy of the data at any point, you can just use:
$new_copy = $row;

Categories