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
Related
I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.
My JSON:
{"data":{"addresses":{"bitcoincash":"qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778","bitcoin":"1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu","ethereum":"0xd7410e84e9c336937637e3cb472ad112c258ede3","litecoin":"LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"},"code":"PGVD745Y","created_at":"2018-08-18T04:26:23Z","description":"dddd","expires_at":"2018-08-18T05:26:23Z","hosted_url":"https://commerce.coinbase.com/charges/example","id":"ddd","metadata":{"customer_id":"IuYBD5X7ylEV6g0xyTWi","name":"Guest#localhost.com"},"name":"ddd","payments":[],"pricing":{"local":{"amount":"19.85","currency":"USD"},"ethereum":{"amount":"0.063584000","currency":"ETH"},"bitcoin":{"amount":"0.00303719","currency":"BTC"},"bitcoincash":{"amount":"0.03345637","currency":"BCH"},"litecoin":{"amount":"0.32861518","currency":"LTC"}},"pricing_type":"fixed_price","resource":"charge","timeline":[{"status":"NEW","time":"2018-08-18T04:26:23Z"}]}}
My PHP:
$exec = json_encode($exec);
$json = json_decode($exec, TRUE);
echo $json['hosted_url'];
It just returns { always, in fact even if I put $json['safasfsaf'] it would still return {
What is the issue, the JSON is valid?
You can get hosted_url in this way (ERROR: you missing data $json['data']['hosted_url'])
also you can check your desired output here
<?php
$a = '{
"data": {
"addresses": {
"bitcoincash": "qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778",
"bitcoin": "1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu",
"ethereum": "0xd7410e84e9c336937637e3cb472ad112c258ede3",
"litecoin": "LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"
},
"code": "PGVD745Y",
"created_at": "2018-08-18T04:26:23Z",
"description": "dddd",
"expires_at": "2018-08-18T05:26:23Z",
"hosted_url": "https://commerce.coinbase.com/charges/example",
"id": "ddd",
"metadata": {
"customer_id": "IuYBD5X7ylEV6g0xyTWi",
"name": "Guest#localhost.com"
},
"name": "ddd",
"payments": [],
"pricing": {
"local": {
"amount": "19.85",
"currency": "USD"
},
"ethereum": {
"amount": "0.063584000",
"currency": "ETH"
},
"bitcoin": {
"amount": "0.00303719",
"currency": "BTC"
},
"bitcoincash": {
"amount": "0.03345637",
"currency": "BCH"
},
"litecoin": {
"amount": "0.32861518",
"currency": "LTC"
}
},
"pricing_type": "fixed_price",
"resource": "charge",
"timeline": [{
"status": "NEW",
"time": "2018-08-18T04:26:23Z"
}]
}
}';
$json = json_decode($a, TRUE);
echo "<pre>";
print_r($json['data']['hosted_url']);
You have error reporting turned off
This error is hidden for you
Warning: Illegal string offset 'hosted_url'
You can turn error reporting on with this code
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
For your code you need to replace $json['hosted_url'] with $json['data']['hosted_url']
$exec = getJson();
$json = json_decode($exec, TRUE);
echo $json['data']['hosted_url'];
Also response is already json so you must not json_encode it
I have noticed that, you are decode json data two time, so you are getting errors.
Hi, i have tried this way.
$exe = '{"data":{"addresses":{"bitcoincash":"qzx3k8cq2e66k4glnt2derr5mppzc6xmvuxgsyp778","bitcoin":"1GjKuo1Q9sw8NytE31J5RPnVpYpEzp47hu","ethereum":"0xd7410e84e9c336937637e3cb472ad112c258ede3","litecoin":"LiQCBwuvW4RVuAg2dBNzS4fkviDwi8EBKa"},"code":"PGVD745Y","created_at":"2018-08-18T04:26:23Z","description":"dddd","expires_at":"2018-08-18T05:26:23Z","hosted_url":"https://commerce.coinbase.com/charges/example","id":"ddd","metadata":{"customer_id":"IuYBD5X7ylEV6g0xyTWi","name":"Guest#localhost.com"},"name":"ddd","payments":[],"pricing":{"local":{"amount":"19.85","currency":"USD"},"ethereum":{"amount":"0.063584000","currency":"ETH"},"bitcoin":{"amount":"0.00303719","currency":"BTC"},"bitcoincash":{"amount":"0.03345637","currency":"BCH"},"litecoin":{"amount":"0.32861518","currency":"LTC"}},"pricing_type":"fixed_price","resource":"charge","timeline":[{"status":"NEW","time":"2018-08-18T04:26:23Z"}]}}';
$data = json_decode($exe, TRUE);
echo $data['data']['hosted_url'];
This is my php file code where i am fetching data from thecatapi
i needed the specific format for datatable
$xml=file_get_contents('https://thecatapi.com/api/images/get?format=xml&results_per_page=3');
$xml = new SimpleXMLElement($xml);
$datas=array();
$datas['rows'] = $xml->data->images;
echo json_encode($datas, true);
Output is:
{"total":50,
"rows":{"image":[
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id":"e0i",
"source_url":"http:\/\/thecatapi.com\/?id=e0i"
},
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id":"MTYwNDE0MQ",
"source_url":"http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},{
"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id":"bon",
"source_url":"http:\/\/thecatapi.com\/?id=bon"
}
]
}
}
but i wanted in this json form
{
"total": 800,
"rows": [
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
Just came up with an alternativ solution. Change this line:
$datas['rows'] = $xml->data->images;
to this:
$datas['rows'] = $xml->data->images->image;
otherwise you can still do this
Decode the json string into an object and modify it suit your needs.
$stdClassObject = json_decode($jsonData);
$stdClassObject->rows = $stdClassObject->rows->image;
$newJsonData = json_encode($stdClassObject, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($newJsonData);
echo '</pre>';
New output:
{
"total": 50,
"rows": [
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id": "e0i",
"source_url": "http:\/\/thecatapi.com\/?id=e0i"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id": "MTYwNDE0MQ",
"source_url": "http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id": "bon",
"source_url": "http:\/\/thecatapi.com\/?id=bon"
}
]
}
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 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;
?>