Using PHP to store results of a post request - php

Im currently working with an API which requires we send our collection details in xml to their server using a post request.
Nothing major there but its not working, so I want to output the sent xml to a txt file so I can look at actually whats being sent!!
Instead of posting to the API im posting to a document called target, but the xml its outputting its recording seems to be really wrong. Here is my target script, note that the posting script posts 3 items, so the file being written should have details of each post request one after the other.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// get the request data...
$payload = '';
$fp = fopen('php://input','r');
$output_file = fopen('output.txt', 'w');
while (!feof($fp)) {
$payload .= fgets($fp);
fwrite($output_file, $payload);
}
fclose($fp);
fclose($output_file);
?>
I also tried the following, but this just recorded the last post request so only 1 collection item was recorded in the txt file, instead of all 3
output_file = fopen('output.txt', 'w');
while (!feof($fp)) {
$payload .= fgets($fp);
}
fwrite($output_file, $payload);
fclose($fp);
fclose($output_file);
I know im missing something really obvious, but ive been looking at this all morning!

Change
$output_file = fopen('output.txt', 'w');
to
$output_file = fopen('output.txt', 'a');
Also, change
$payload .= fgets($fp);
to
$payload = fgets($fp);

you should probably use curl instead to fetch the content and then write it via fwrite

change
$payload .= fgets($fp);
to
$payload = fgets($fp);

Related

Recieving Blank/No Response to Status Update Notification(statusUpdateNotification) from Apple Server - PHP v5.4.43

We have set up a URL in the app profile in iTunes and our server has cleared the ATS security criteria.
Following are the codes that we have tried to implement :
$data = json_decode(file_get_contents('php://input'), true);
$fp = fopen('appdata.txt', 'a');
fwrite($fp, $data);
fclose($fp);
We got no response with this code.
Then we tried -
$data = print_r($_REQUEST, TRUE);
$fp = fopen('appdata.txt', 'a');
fwrite($fp, $data);
fclose($fp);
We get a blank array in our 'appdata.txt' file as -
Array
(
)
Is there any way to find out if we are even receiving a response from Apple server?
Finally, we have solved the issue :)
While checking error log file we find this error message -
PHP Warning: "fwrite() expects parameter 2 to be string, array given."
So we replaced this line in our first code -
fwrite($fp, $data);
with this -
fwrite($fp, print_r($data, true));
Now the code is working fine and we are getting the Status Update Notification every time.

PHP: Adding entries from php to json

I have no knowledge of php, but from an iOS app I am trying to pass variables to json which can be accessible later, each time user complete level the post method push 3 variables and its value which adds that info into file like this
php code:
<?php
header ('Location: ');
$handle = fopen("data.json", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, ":");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
and I get the output like this after two users used post method:
Name:user1
Points:100
Level:1
Name:user2
Points:200
Level:2
can someone please help me to get json format output, with every time user push data with the post method it adds info to existing data instead of overwriting it?
I want output like this:
[
{"Name":"user1","Score":"100","Level":"1"},{"Name":"user2","Score":"200","Level":"2"}
]
<?php
$json = json_decode(file_get_contents("data.json"), true);
$json[] = json_encode($_POST);
file_put_contents("data.json", $json);
This decodes the current JSON file, then appends the new information and then saves over the existing JSON file.

Getting resulting data from website query

I need to get the resulting data from a website query. for example
http://www.uniprot.org/uniprot/?query=organism:9606+AND+gene:AEBP1+AND+reviewed:yes&sort=score&format=tab&columns=entry%20name
resulting page shows
Entry name
AEBP1_HUMAN
I need the result, in this case "AEBP1_HUMAN" to be display on my website. Confused how to get it. Thanks
The goal is, that you can read the content of any url like a file, because php supports wrappers for variety of protocols.
First example uses function file that read entire content and split it by lines into an array.
<?php
$content = file($url);
echo $content[1];
?>
In the second example you get the whole content as a string, so you have to split it with explode function by line endings.
<?php
$content = file_get_contents($url);
$lines = explode("\n", $content);
echo $lines[1];
?>
Third example uses standard file open in combination with function fgets that read the content line by line.
<?php
$fp = fopen($url);
$fp = fopen($url, 'r');
$line = fgets($fp);
$line = fgets($fp);
echo $line;
?>
The last example shows usage of curl. Don't forget to use right options.
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
$lines = explode("\n", $content);
echo $lines[1];
?>
Sometimes you may experience problems on public hosting servers, where reading remote content is blocked.

How to parse JSON into CSV in PHP for Social Mention API

I need to query SocialMention.com for "Colorado Springs" and "District 11" and pull the data back into a CSV file. I'm an old programmer but new to PHP and JSON. Here's the simple php code:
<?php
$curl = curl_init('http://api.socialmention.com/search?q=%22colorado+springs%22+%22district+11%22&f=json&src[]=twitter&sentiment=true&meta=info');
$result = curl_exec($curl);
echo $result;
?>
How do I parse $result and store it in a CSV file? I've been researching this for 6 days and have tried every example I can find with no luck. In the examples below I keep getting an "Invalid argument in foreach" error.
Your question is broad since you don't really say how you want to parse $result, but you're not even getting $result because curl_exec will actually print out its contents. Instead you can set curl_setopt($curl, CURLOPT_RETURNTRANSFER, true), or you can probably just use$result = file_get_contents($url);
Anyway, you can change the result from JSON to usable PHP data structure via $data = json_decode($result, true). The second argument forces associative arrays, which are probably better for your purposes.
Then you can write to the CSV file:
$fh = fopen('csvfile', 'w');
foreach ($result['items'] as $items) {
fputcsv($fh, $items);
}
u can refer the two links too
1.Parsing JSON file with PHP
2.php writing to csv from an array
$json_a=json_decode($string,true); //decodes json
//writes to csv
$fp = fopen('file.csv', 'w');
for ($i = 0; $i < count($json_a); $i++) {
$fields = //json object feids here
fputcsv($fp, $fields);
}
fclose($fp);

How to speed up file_get_contents?

Here's my code:
$language = $_GET['soundtype'];
$word = $_GET['sound'];
$word = urlencode($word);
if ($language == 'english') {
$url = "<the first url>";
} else if ($language == 'chinese') {
$url = "<the second url>";
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"User-Agent: <my user agent>"
)
);
$context = stream_context_create($opts);
$page = file_get_contents($url, false, $context);
header('Content-Type: audio/mpeg');
echo $page;
But I've found that this runs terribly slow.
Are there any possible methods of optimization?
Note: $url is a remote url.
It's slow because file_get_contents() reads the entire file into $page, PHP waits for the file to be received before outputting the content. So what you're doing is: downloading the entire file on the server side, then outputting it as a single huge string.
file_get_contents() does not support streaming or grabbing offsets of the remote file. An option is to create a raw socket with fsockopen(), do the HTTP request, and read the response in a loop, as you read each chunk, output it to the browser. This will be faster because the file will be streamed.
Example from the Manual:
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
header('Content-Type: audio/mpeg');
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
The above is looping while there is still content available, on each iteration it reads 128 bytes and then outputs it to the browser. The same principle will work for what you're doing. You'll need to make sure that you don't output the response HTTP headers which will be the first few lines, because since you are doing a raw request, you will get the raw response with headers included. If you output the response headers you will end up with a corrupt file.
Instead of downloading the whole file before outputting it, consider streaming it out like this:
$in = fopen($url, 'rb', false, $context);
$out = fopen('php://output', 'wb');
header('Content-Type: video/mpeg');
stream_copy_to_stream($in, $out);
If you're daring, you could even try (but that's definitely experimental):
header('Content-Type: video/mpeg');
copy($url, 'php://output');
Another option is using internal redirects and making your web server proxy the request for you. That would free up PHP to do something else. See also my post regarding X-Sendfile and friends.
As explained by #MrCode, first downloading the file to your server, then passing it on to the client will of course incur a doubled download time. If you want to pass the file on to the client directly, use readfile.
Alternatively, think about if you can't simply redirect the client to the file URL using a header("Location: $url") so the client can get the file directly from the source.

Categories