I am trying to parse a simple response from the server and use its values.
I was able to get the required information as follows:
The actual response :
AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success
What I need is separate values for :
AccountID
Authenticated
ResponseCode
ResponseText
My code so far :
$tempValue = explode("\n", $response);
foreach($tempValue as $row => $data)
{
//get row data
$row_data = explode('&', $data);
$row_internal = explode('=', $row_data);
$info2[$row]['id'] = $row_internal[0];
$info2[$row]['name'] = $row_internal[1];
$info2[$row]['description'] = $row_internal[2];
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
echo 'Account ID: ' . $info[$row]['id'] . '<br />';
echo 'Authenticated: ' . $info[$row]['name'] . '<br />';
echo 'Response Code: ' . $info[$row]['description'] . '<br />';
echo '<br></br>';
echo 'Account ID: ' . $info2[$row]['id'] . '<br />';
echo 'Authenticated: ' . $info2[$row]['name'] . '<br />';
echo 'Response Code: ' . $info2[$row]['description'] . '<br />';
}
Result for the above code :
Account ID: AccountID=0
Authenticated: Authenticated=1
Response Code: ResponseCode=0
Account ID:
Authenticated:
Response Code:
What I needed was just the values for the fields like :
Account ID: 0
Authenticated: 1
Response Code: 0
If this is a query string response, then no need to explode, there is a better tool that handles this well.
Just use parse_str().
Simple one line response example:
$response = 'AccountID=0&Authenticated=1&ResponseCode=0&ResponseText=Success';
parse_str($response, $data);
echo '<pre>';
print_r($data);
Or if the response looks like a multiline string like this, you could apply it like:
$response = "AccountID=1&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=2&Authenticated=1&ResponseCode=0&ResponseText=Success
AccountID=3&Authenticated=1&ResponseCode=0&ResponseText=Success
";
$responses = explode("\n", $response);
foreach ($responses as $key => $value) {
parse_str($value, $data);
if(!empty($data)) {
echo 'Account ID: '.$data['AccountID'] .'<br/>';
echo 'Authenticated: '.$data['Authenticated'] .'<br/>';
echo 'Response Code: '.$data['ResponseCode'] .'<br/>';
echo 'Response Text: '.$data['ResponseText'] .'<br/>';
echo '<br/>';
}
}
Related
does not work with a nested element
the elements of the first level are output, and the nested array with data is not read, as it is possible to get values - id, title and location?
<?php
function removeBomUtf8($s){
if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
return substr($s,3);
}else{
return $s;
}
}
$url = "https://denden000qwerty.000webhostapp.com/opportunities.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);
while ($el_name = current($decoded)) {
// echo 'total = ' . $el_name->total_items . 'current = ' . $el_name->current_page . 'total = ' . $el_name->total_pages . '<br>' ;
echo ' id = ' . $el_name->data[0]->id . ' title = ' . $el_name->data.title . ' location = ' . $el_name->data.location . '<br>' ;
next($decoded);
}
?>
$el_name->data[0]->id is correct
$el_name->data.title is not
you see the difference?
and $decoded is the root (no need to iterate over it) - you want to iterate over the data children
<?php
foreach($decoded->data as $data)
{
$id = (string)$data->id;
$title = (string)$data->title;
$location = (string)$data->location;
echo sprintf('id = %s, title = %s, location = %s<br />', $id, $title, $location);
}
I am very beginner in programmer and I am learning.
I am sorry if my question is too bad.
I want to create variable in php from api content, for example:
This contents is from this URL: http://example.com/api
{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}
<?php
$content = file_get_contents("http://example.com/api");
$content = str_replace('"', "", $content);
$content = str_replace(":", "=", $content);
$content = str_replace(",", "&", $content);
parse_str($content);
echo $name; //John
echo $age; //20
echo $genre; //male
echo $language //[{id <======== here is my problem
?>
My problem is when I am getting an array like "language", how to fix it?
Thanks for help.
U can use the http://www.php.net/json_decode in two ways :
This is object oriented :
$str = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
$json = json_decode($str);
echo 'name: ' . $json->{'name'} .'<br>';
echo 'age: ' . $json->{'age'} .'<br>';
echo 'genre: ' . $json->{'genre'} . '<br>';
foreach($json->{'language'} as $data){
echo 'id: ' . $data->{'id'} . '<br>';
echo 'name: ' . $data->{'name'} . '<br>';
}
As an associative array :
$json = json_decode($str, true);
echo 'name: ' . $json['name'] .'<br>';
echo 'age: ' . $json['age'] .'<br>';
echo 'genre: ' . $json['genre'] . '<br>';
foreach($json['language'] as $data){
echo 'id: ' . $data['id'] . '<br>';
echo 'name: ' . $data['name'] . '<br>';
}
json_decode() will help you to convert the string data to something more accessible:
<?php
// Instead of your fetched data we use static example data in this script
//$content = file_get_contents("http://example.com/api");
$content = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
// Convert json data to object
$data = json_decode($content);
// access object properties by using "->" operator
echo $data->name;
echo $data->age;
echo $data->genre;
// language is an array of objects, so let's look at each language object...
foreach($data->language as $lang) {
// ... and extract data using "->" again
echo $lang->id;
echo $lang->name;
}
A live example of this code can be found at http://sandbox.onlinephpfunctions.com/code/6df679c3faa8fff43308a34fb80b2eeb0ccfe47c
As pointed out by #fusionK, the response from the api request is a json string so convert to an object ( or array if preferred ) using json_decode ( json_decode( $data,true ) for an array )
Once it is decoded it is straightforward to access the properties of the object.
<?php
/* capture and decode response from api - creates an object */
$content = json_decode( file_get_contents("http://example.com/api") );
/* using object notation to access properties */
echo $content->name.' '.$content->age.' '.$content->genre;
/* for the language which is an array of objects */
$lang=$content->language;
foreach( $lang as $language ){
$obj=(object)$language;
echo $obj->id.' '.$obj->name;
}
?>
I have a JSON file called from an URL. I've checked and I'm getting the the data from the URL.
I've tried a lot, but I can't get the loop foreach to work - what is wrong?
<?php
$url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/GetCarsExtended/59efc61e-ceb2-463b-af39-80348d771999';
$json= file_get_contents($url);
$data = json_decode($json);
$rows = $data->{'contents'};
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->{'contents'}->{'FabrikatNavn'};
$ModelNavn = $row->{'contents'}->{'ModelNavn'};
$PrisDetailDkk = $row->{'contents'}->{'PrisDetailDkk'};
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
?>
The actual problem is you trying to access content object again. Just change your foreach snippet with,
foreach ($rows as $row) {
echo '<p>';
$FabrikatNavn = $row->FabrikatNavn;
$ModelNavn = $row->ModelNavn;
$PrisDetailDkk = $row->PrisDetailDkk;
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
DEMO.
Use json_decode($data, true) so that it parses the JSON content into a PHP array. So it will be something like
$rows = $data['contents'];
foreach($rows as $row) {
echo '<p>';
$FabrikatNavn = $row['contents']['FabrikatNavn'];
$ModelNavn = $row['contents']['ModelNavn'];
$PrisDetailDkk = $row['contents']['PrisDetailDkk'];
echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
echo '</p>';
}
Take a look at using json_decode($json, true) as this will convert the data to an associative array which seems to be the way you are approaching the solution.
Check the output by printing with var_dump() or print_r()
Try like this
$data = json_decode($json,true); //decode json result as array and thenloop it
print '<pre>';
print_r($data);
foreach($data as $row){
//do something here
}
That's my first post here on SO.
I'm using PHP to get Facebook friends statuses. In particular, I've tried to retrieve all public statuses from one of my facebook friends, but it happens only the first 100 statuses. I need to get all the statuses and to write them in a text file. this is the code I'm using, patched up from many answers I read here on SO.
$i=0;
$result = $facebook->api('/my_friend_ID/statuses/',
array('access_token' => $facebook->access_token,'limit'=>100,));
//'offset'=>50,used before limit, it push the limits forward by 50, it doesn't go beyond it
//'since'=>2010, I read on SO there was even this field, but I can't make it work.
foreach($result['data'] as $post)
{
echo $i . '<br>';
echo $post['id'] . '<br>';
echo $post['from']['name'] . '<br>';
echo $post['from']['id'] . '<br>';
echo $post['name'] . '<br>';
echo $post['message'] . '<br>';
echo '*---------------------------------------------------*' . '<br>';
$i++;
$write_file = fopen("esempio.txt","a");
$message = $post['message'] . '<br>';
fwrite($write_file,$message);
fclose($write_file);
}
so, to be clearer, how to get all friends statuses (old and new) in a text file?
You need to use paging https://developers.facebook.com/docs/reference/api/pagination/
$the_statuses = array();
$your_statuses = $facebook->api("/my_friend_ID/statuses/");
while ($your_statuses['data'])
{
$the_statuses = array_merge( $the_statuses, $your_statuses['data'] );
$paging = $your_statuses['paging'];
$next = $paging['next'];
$query = parse_url($next, PHP_URL_QUERY);
parse_str($query, $par);
$your_statuses = $facebook->api(
"/my_friend_ID/statuses/", 'GET', array(
'limit' => $par['limit'],
'until' => $par['until'] ));
}
Then you can do the loop through all statuses
foreach($the_statuses['data'] as $post)
{
echo $i . '<br>';
echo $post['id'] . '<br>';
echo $post['from']['name'] . '<br>';
echo $post['from']['id'] . '<br>';
echo $post['name'] . '<br>';
echo $post['message'] . '<br>';
echo '*---------------------------------------------------*' . '<br>';
$i++;
$write_file = fopen("esempio.txt","a");
$message = $post['message'] . '<br>';
fwrite($write_file,$message);
fclose($write_file);
}
I am trying to use php to parse a JSON feed of posts using Facebook Graph API
I found the following solution for comments...
<?php
$request_url ="https://graph.facebook.com/comments/?
ids=http://www.youtube.com/watch?v=fyF-fj-1coY&feature=player_embedded";
$requests = file_get_contents($request_url);
$fb_response = json_decode($requests);
foreach ($fb_response as $key => $response) {
foreach ($fb_response->$key as $data) {
foreach ($data as $item) {
echo 'NAME: ' . $item->name . '<br />';
echo 'From ID: ' . $item->from->id . '<br />';
echo 'From Name: ' . $item->from->name . '<br />';
echo 'Message: ' . $item->message . '<br />';
echo 'Timestamp: ' . $item->created_time . '<br /><br />';
}
}
}
?>
This is the url id I'm working with: https://graph.facebook.com/210849652406/feed/?access_token={VALID_USER_TOKEN}
I just don't know how to call the items for this feed. I'm trying to make the comments parse with this post/feed but I get essentially nothing. I want the basic items like name of the post, caption, etc. I think if I just could get the name of the post I could figure it all out!
You are looping incorrectly
try this
foreach($fb_response->data as $item){
echo 'Message: ' . $item->message . '<br />';//there is no name returned on a comment
echo 'From ID: ' . $item->from->id . '<br />';
echo 'From Name: ' . $item->from->name . '<br />';
echo 'Message: ' . $item->message . '<br />';
echo 'Timestamp: ' . $item->created_time . '<br /><br />';
}
Do you have warnings/errors displayed? Ensure that you have extension=php_openssl.dll (or .so) enabled in your php.ini or you will get no results. This is because you are fetching from a secure site.
Also $item->name is an undefined property in the JSON. Perhaps you mean $item->id. Everything else looks ok.
Why aren't you using the PHP SDK?
https://developers.facebook.com/docs/reference/php/