I have a TXT file containing some facebook Open Graph info like this:
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes?format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
In PHP, I want to extract all the id numbers from the rows that show
"id": "XXXXXXXXXXXX",
The output should look like this:
I like 8277564344063
I like 243564344063
I started the following but I am getting an error:
<?php
$file_handle = fopen("raw.txt", "rb");
ob_start();
$text = file_get_contents('raw.txt');
$decode = json_decode($text);
print_r($decode);
$new_content = ob_get_clean();
file_put_contents("likes.txt", $new_content);
fclose($file_handle);
?>
The error is that my output is blank! What am I doing wrong?
Please help?
You don't have valid JSON.
The JSON Object below this line is valid JSON. I removed the comma after your last associative array within your "data" array. You shouldn't need a comma at the end of the array.
{
"data": [
{
"name": "Avatar",
"category": "Movie",
"id": "82771544063",
"created_time": "2012-04-13T21:16:56+0000"
},
{
"name": "HappyDance",
"category": "Movie",
"id": "243564344063",
"created_time": "2012-04-13T21:16:56+0000"
}
],
"paging": {
"next": "https://graph.facebook.com/me/likes? format=json&limit=5000&offset=5000&__after_id=5546653546361"
}
}
Parse error on line 14:
... }, ], "paging": {
---------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
As I removed the comma from the non-valid JSON. I was able to get the result you wanted.
<?php
$json_object = file_get_contents('fb.json');
if(!$json_object) {
echo "oops, cant read the file";
}
// remap json_object
$json_object = json_decode($json_object,true);
foreach($json_object['data'] as $item) {
$items[] = "I like" . ' ' . $item['id'];
/* If you want to just echo " I like xyz" etc
* use echo "I like" . $item['id'];
*/
}
$list = implode(',',$items);
echo $list;
?>
Related
How can I output this json to csv properly?
My json file pattern is like this:
{
"swimmers": [
{
"Province": "Ontario",
"Exemption": "S9,SB9,SM9",
"Code": "A,3,4",
"Level": "Level 8",
"ClassificationDate": "2020",
"RYEar": "2024",
"Status": "Registered",
"ID": "123456",
"FirstName": "John",
"LastName": "Doe",
"Gender": "M",
"AGE": null,
"DOB": "01/11/2000",
"Clubs": [
{
"Clubname": "Human Fish",
"Code": "ABC",
"Clubid": "300"
}
],
"Email": null,
"Language": "E",
"ChallengeData": null
}
//more entries with same pattern as first
],
"status": "OK",
"application": "SOme App API"
}
I had success to turn it into a csv with the code below but I'm unable to output the clubs field in the csv file, instead of showing the club, it just shows "Array()". I tried to fix that with the commented code but it doesn't solve the problem.
$csvFileName = 'converted.csv';
$json = 'myjson.json';
$data = file_get_contents($json);
$payload= json_decode($data);
$file_pointer = fopen($csvFileName, 'w');
if ($file_pointer){
foreach($payload['swimmers'] as $row) {
// $clubs = $row['Clubs'] ;
// if (is_array($clubs)){
// foreach($clubs as $c){
// fputcsv($file_pointer, $c);
// }
// }else{
fputcsv($file_pointer, $row);
}
}
Append each element of the Clubs field to $row, then remove the Clubs field.
foreach ($payload['swimmers'] as $row) {
foreach ($row['Clubs'] as $club) {
$row = array_merge($row, array_values($club));
}
unset($row['Clubs']);
fputcsv($file_pointer, $row);
}
I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2
My code:
$json_response = json_decode($response, true);
$tag= $json_response['results']['tags'][0]['tag'];
print $tag;
My JSON:
{
"results": [
{
"tagging_id": null,
"image": "image.jpg",
"tags": [
{
"confidence": 100,
"tag": "herb"
},
{
"confidence": 98.3637619018555,
"tag": "plant"
}
]
}
]
}
I am trying to output "herb". I have looked up through examples but cannot figure out where the bug is.
I am reading results and then the trees.
You have to fetch the first element inside ['results'].
echo $json_response['results'][0]['tags'][0]['tag'];
I have a json file like this
{
"id": "123456789012345",
"members": {
"data": [
{
"name": "Dylan John",
"administrator": false,
"id": "12341234"
},
{
"name": "Test user",
"administrator": false,
"id": "43214321"
},
{
"name": "Demo user",
"administrator": false,
"id": "55445544"
},
{
"name": "Fake user",
"administrator": false,
"id": "11991199"
}
],
"paging": {
"next": "www.123456demo12345.com"
}
}
}
I need to extract the id of each name.
I just start my php code like that but simply display only the master id:
<?php
$url = "http://www.1234demo1234fake.com/user.json";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[id]; //echo master id
echo $data[members][data][id];
?>
You have to iterate over $data['members']['data'] and print $data['members']['data'][$i]['id'].
Your JSON object contains property members again members has property data.
Now data is an array.
Just loop over data, you get array of objects (members), fetch property id from it.
<?php
$abc = json_decode($your_json_sting);
$membersData = $abc->members->data;
$memberIds = array();
foreach ($membersData as $mem) {
$memberIds[] = $mem->id;
}
echo '<pre>';print_r($memberIds);echo '</pre>';
?>
I've this JSON string:
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
}
}';
I'd like to print every single entry on a webpage using php and then save these entries on a mysql db.
In the db there is already a "code", "name" and "link" field..
This is what I've tried without luck (to print the stuff on a page):
$obj = json_decode($json,true);
echo ($obj["bigprodlist"]["prods"][0]["name"]);
Thank you very much for the help
First, fix your JSON missing end bracket that makes JSON decoding fail (add the ] after the prods data ), then expand your echo statement with some foreach loops to get the data printed. This is only a simple example to get you on the right track:
foreach ($obj["bigprodlist"]["prods"] as $p):
echo "<div>";
foreach ($p as $name=>$value):
echo "<span>".$name.": ".$value."</span>";
endforeach;
echo "</div>";
endforeach;
You can then use the same loop procedure to get the data into your DB.
You need to use json_last_error(); http://no1.php.net/manual/en/function.json-last-error.php
Debugging:
$obj = json_decode($json,true);
var_dump($obj, json_last_error());
You are missing a ] :
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
] //missing!
}
}';
Where did you get json output?
It's invalid:
Parse error on line 18:
... } } }
----------------------^
Expecting ',', ']'
Check your json at http://jsonlint.com/