Converting JSON from URL to CSV with PHP - php

When I run the code below it results in the first row in a long list of columns containing only the text Array.
I've used $decoded = json_decode($json_file, true); to indicate that I want arrays instead of objects so I'm not sure what the issue is.
Should I be using bracket or arrow notation somewhere to specify that I want the array values?
$json_file = file_get_contents('https://fakeurl.com&contentType=json', false);
$decoded = json_decode($json_file, true);
$fp = fopen('output.csv', 'w');
foreach($decoded as $comment) {
fputcsv($fp, $comment);
}
fclose($fp);
Here is a small snippet of the JSON. It looks like this all the way through:
{
"rows": [{
"columns": [{
"name": "clientId",
"value": "1839",
"type": "xs:int",
"format": ""
}, {
"name": "campaignId",
"value": "25646",
"type": "xs:int",
"format": ""
}, {
"name": "campaignStatus",
"value": "Live",
"type": "xs:string",
"format": ""
}, {
"name": "campaignName",
"value": "Template Donation Litle",
"type": "xs:string",
"format": ""
}, {
"name": "campaignExportName",
"value": "Template Donation Litle",
"type": "xs:string",
"format": ""
}, {
"name": "description",
"value": "/donate/template/Litle",
"type": "xs:string",
"format": ""
}]
}, {
"columns": [{
"name": "clientId",
"value": "1839",
"type": "xs:int",
"format": ""
}, {
"name": "campaignId",
"value": "25812",
"type": "xs:int",
"format": ""
}, {
"name": "campaignStatus",
"value": "Live",
"type": "xs:string",
"format": ""
}, {
"name": "campaignName",
"value": "Monthly Only",
"type": "xs:string",
"format": ""
}, {
"name": "campaignExportName",
"value": "Monthly Only",
"type": "xs:string",
"format": ""
}, {
"name": "description",
"value": "A donation receipt will be emailed to the address you submitted. This donation is tax-deductible to the fullest extent of the law.",
"type": "xs:string",
"format": ""
}]
}]
}

Your array is much deeper and the values need to be extracted:
foreach($decoded['rows'] as $row) {
$values = array_column($row['columns'], 'value');
fputcsv($fp, $values);
}
If you want the names/headers in the first row then you need to do this before the loop:
$headers = array_column($decoded['rows'][0]['columns'], 'name');
fputcsv($fp, $headers);

Related

Extract element from nested JSON

There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.

How to validate required items of JSON SCHEMA array

I have a JSON Schema for new orders, that consists of order list and address.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"properties": {
"order": {
"type": "array",
"items": {
"type": "array",
"properties": {
"product_id": {
"type": "integer"
},
"quantity": {
"type": "integer"
}
},
"required": [
"product_id",
"quantity"
]
}
},
"address": {
"type": "array",
"properties": {
"name": {
"type": "string"
},
"phone": {
"type": "integer"
},
"address1": {
"type": "string"
},
"address2": {
"type": "string"
},
"city": {
"type": "string"
},
"state_or_region": {
"type": "string"
},
"country": {
"type": "string"
}
},
"required": [
"name",
"phone",
"address1",
"city",
"state_or_region",
"country"
]
}
},
"required": [
"order",
"address"
]
}
But it doesn't seem to actually validate the items at all (I'm using Laravel 5.2 with "justinrainbow/json-schema": "~2.0" ):
$refResolver = new \JsonSchema\RefResolver(new \JsonSchema\Uri\UriRetriever(), new \JsonSchema\Uri\UriResolver());
$schema = $refResolver->resolve(storage_path('schemas\orders.post.json'));
$errors = [];
$input = Request::input();
// Validate
$validator = new \JsonSchema\Validator();
$validator->check($input, $schema);
$msg = [];
if ($validator->isValid()) {
return Response::json(['valid'], 200, [], $this->pritify);
} else {
$msg['success'] = false;
$msg['message'] = "JSON does not validate";
foreach ($validator->getErrors() as $error) {
$msg['errors'][] = [
'error' => ($error['property'] = ' ') ? 'wrong_data' : $error['property'],
'message' => $error['message']
];
}
return Response::json($msg, 422, [], $this->pritify);
}
A request like this always comes valid:
{
"order": [
{
"product_id": 100,
"quantity": 1
},
{
"product_id": 0,
"quantity": 2
}
],
"address": []
}
Any ideas what am I doing wrong?
You have messed array and object types. The only array value in your scheme must be order. Fixed scheme:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"order": {
"type": "array",
"items": {
"type": "object",
"properties": {
"product_id": {
"type": "integer"
},
"quantity": {
"type": "integer"
}
},
"required": [
"product_id",
"quantity"
]
}
},
"address": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"phone": {
"type": "integer"
},
"address1": {
"type": "string"
},
"address2": {
"type": "string"
},
"city": {
"type": "string"
},
"state_or_region": {
"type": "string"
},
"country": {
"type": "string"
}
},
"required": [
"name",
"phone",
"address1",
"city",
"state_or_region",
"country"
]
}
},
"required": [
"order",
"address"
]
}
And validation errors I got with you test data:
JSON does not validate. Violations:
[address.name] The property name is required
[address.phone] The property phone is required
[address.address1] The property address1 is required
[address.city] The property city is required
[address.state_or_region] The property state_or_region is required
[address.country] The property country is required

Retrieving likes of Facebook Posts in php

I am looking for a way to retrieve the number of likes of a Facebook post, based on its post_id. I got hold of a php code from this forum itself..and it's something like
<?php
function fetchUrl($url){
return file_get_contents($url);
}
$json_object = fetchUrl("https://graph.facebook.com/{post_id}/likes?access_token={token}&limit=5000000"); //
$feedarray = json_decode($json_object, true);
$likesNum = count($feedarray['data']); // return the number of items in `data` array
print $likesNum;
?>
But the problem is this method does not retrieve the total likes of a post, since likes are displayed in blocks of 1000, after which theres another link to a different page containing the next set of 1000 likes and so on.
Is there a way to get the total number of likes of a facebook post by a single query?
Add the summary flag ** summary=true**
"https://graph.facebook.com/{post_id}/likes?access_token={token}&summary=true"
{
"data": [
{
"id": "663342380429664",
"name": "Luis Mendoza"
},
{
"id": "1532100840406448",
"name": "Sakazuki Akainu"
},
{
"id": "780666205412913",
"name": "Joaito KoRn"
},
{
"id": "1060933433919925",
"name": "Adrian Sosa"
},
{
"id": "860704407276452",
"name": "Sarah Rosenstrauch"
},
{
"id": "1947974762009431",
"name": "David Prieto"
},
{
"id": "804864302928112",
"name": "Ronal Ortega"
},
{
"id": "1505075359814934",
"name": "Gonzalo Larzen"
},
{
"id": "1431207613804483",
"name": "Victor Clc"
},
{
"id": "508785009283633",
"name": "Rxdry EzDe Cerrx Mcmxii"
},
{
"id": "435355413265946",
"name": "Ángel Fernando Huillca Alonso"
},
{
"id": "163773913961445",
"name": "Pelado Miguel Pin Macias"
},
{
"id": "1479227465674392",
"name": "Releck Solitario"
},
{
"id": "161610054193539",
"name": "MD Sahin MD Sahin"
},
{
"id": "798431050242097",
"name": "Brian Nahuel"
},
{
"id": "624869574305480",
"name": "Saul Alfredo"
},
{
"id": "1642733362665392",
"name": "Junior Zurita"
},
{
"id": "134907406871404",
"name": "Wil Peña"
},
{
"id": "10153052770952668",
"name": "Miguel Peña Cáceres"
},
{
"id": "1461494580846182",
"name": "Darian Suarez"
},
{
"id": "365762500250317",
"name": "Igarashi Ganta"
},
{
"id": "750032685093387",
"name": "Camila Barbé"
},
{
"id": "781013541941152",
"name": "Gonzalo Nievas"
},
{
"id": "756520927743339",
"name": "Jonathan C. Duran Cuellar"
},
{
"id": "1504488093199860",
"name": "Maxi Russo"
}
],
"paging": {
"cursors": {
"before": "NjYzMzQyMzgwNDI5NjY0",
"after": "MTUwNDQ4ODA5MzE5OTg2MAZDZD"
},
"next": "https://graph.facebook.com/v2.3/1009501939072385/likes?access_token=TOKEN..."
},
"summary": {
"total_count": 4303
}
}

Phrasing Json response in PHP

So I have come to a slight issue in phrasing this api response.
I'm trying to phrase the screenshot data from this api response?..
I have tried the below but to no avail!.. It just seems to be NULL?..
any help would be great thanks
$jsonData = json_decode($response, true);
$testt = $jsonData->screenshot->data;
The response:
{
"kind": "pagespeedonline#result",
"id": "http://stackoverflow.com/",
"responseCode": 200,
"title": "Stack Overflow",
"score": 78,
"pageStats": {
"numberResources": 31,
"numberHosts": 11,
"totalRequestBytes": "4412",
"numberStaticResources": 22,
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidLandingPageRedirects": {
"localizedRuleName": "Avoid landing page redirects",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your page has no redirects. Learn more about avoiding landing page redirects.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/AvoidRedirects"
}
]
}
}
]
},
"EnableGzipCompression": {
"localizedRuleName": "Enable compression",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "You have compression enabled. Learn more about enabling compression.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/EnableCompression"
}
]
}
}
]
},
"LeverageBrowserCaching": {
"localizedRuleName": "Leverage browser caching",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "You have enabled browser caching. Learn more about browser caching recommendations.",
"args": [
{
"type": "HYPERLINK"
}
]
}
}
]
},
"MainResourceServerResponseTime": {
"localizedRuleName": "Reduce server response time",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your server responded quickly. Learn more about server response time optimization.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/Server"
}
]
}
}
]
},
"MinifyCss": {
"localizedRuleName": "Minify CSS",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your CSS is minified. Learn more about minifying CSS.",
"args": [
{
"value": "https://developers.google.com/speed/docs/insights/MinifyResources"
}
]
}
}
]
},
"MinifyHTML": {
"ruleImpact": 0.1443,
"urlBlocks": [
{
"header": {
"format": "Compacting HTML code, including any inline JavaScript and CSS contained in it, can save many bytes of data and speed up download and parse times."
}
},
{
"header": {
"format": "Minify HTML for the following resources to reduce their size by $2 ($3 reduction).",
"args": [
{
"value": "https://developers.google.com/speed/docs/insights/MinifyResources"
},
{
"value": "1.4KiB"
},
{
"value": "5%"
}
]
},
"urls": [
{
"result": {
"format": "Minifying $1 could save $2 ($3 reduction) after compression.",
"args": [
{
"type": "URL",
"value": "http://stackoverflow.com/"
},
{
"type": "BYTES",
"value": "1.4KiB"
},
{
"value": "5%"
}
]
}
}
]
}
]
},
"MinifyJavaScript": {
"localizedRuleName": "Minify JavaScript",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your JavaScript content is minified. Learn more about minifying JavaScript.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/MinifyResources"
}
]
}
}
]
},
"MinimizeRenderBlockingResources": {
"localizedRuleName": "Eliminate render-blocking JavaScript and CSS in above-the-fold content",
"urlBlocks": [
{
"header": {
"args": [
{
"type": "INT_LITERAL",
"value": "2"
},
{
"type": "INT_LITERAL",
"value": "3"
}
]
}
},
{
"header": {
"format": "None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML."
}
},
{
"header": {
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/BlockingJS"
}
]
},
"urls": [
{
"result": {
"format": "$1",
"args": [
{
"type": "URL",
"value": "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
}
]
}
},
{
"result": {
"format": "$1",
"args": [
{
"type": "URL",
"value": "http://cdn.sstatic.net/Js/stub.en.js?v=174f553de1d0"
}
]
}
}
]
},
{
"header": {
"format": "Optimize CSS Delivery of the following:",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery"
}
]
},
"urls": [
{
"result": {
"format": "$1",
"args": [
{
"type": "URL",
"value": "http://cdn.sstatic.net/stackoverflow/all.css?v=55bbe6171ff2"
}
]
}
},
{
"result": {
"format": "$1",
"args": [
{
"type": "URL",
"value": "http://cdn-careers.sstatic.net/careers/gethired/company.min.css?v=86ee8c8bfa3e"
}
]
}
},
{
"result": {
"format": "$1",
"args": [
{
"type": "URL",
"value": "http://cdn-careers.sstatic.net/careers/gethired/sidebar.min.css?v=88f3fd5e2263"
}
]
}
}
]
}
]
},
"OptimizeImages": {
"localizedRuleName": "Optimize images",
"ruleImpact": 3.0802000000000005,
"urlBlocks": [
{
"header": {
"format": "Properly formatting and compressing images can save many bytes of data."
}
},
{
"header": {
"format": "Optimize the following images to reduce their size by $2 ($3 reduction).",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/OptimizeImages"
},
{
"type": "BYTES",
"value": "30KiB"
},
{
"type": "PERCENTAGE",
"value": "42%"
}
]
},
"urls": [
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://cdn-careers.sstatic.net/careers/gethired/img/careers4-ad-header-so-crop.png?v=f4ca4345dc81"
},
{
"type": "BYTES",
"value": "16.6KiB"
},
{
"type": "PERCENTAGE",
"value": "73%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://cdn.sstatic.net/img/share-sprite-new.png?v=204b1e0e421b"
},
{
"type": "BYTES",
"value": "2.9KiB"
},
{
"type": "PERCENTAGE",
"value": "19%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://cdn.sstatic.net/Img/sprite-herobox.png?v=d173774f3a9f"
},
{
"type": "BYTES",
"value": "2.8KiB"
},
{
"type": "PERCENTAGE",
"value": "43%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://i.stack.imgur.com/Tfe0K.png"
},
{
"type": "BYTES",
"value": "2.6KiB"
},
{
"type": "PERCENTAGE",
"value": "76%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://i.stack.imgur.com/vobok.png"
},
{
"type": "BYTES",
"value": "2.6KiB"
},
{
"type": "PERCENTAGE",
"value": "76%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b"
},
{
"type": "BYTES",
"value": "1.5KiB"
},
{
"type": "PERCENTAGE",
"value": "9%"
}
]
}
},
{
"result": {
"format": "Losslessly compressing $1 could save $2 ($3 reduction).",
"args": [
{
"type": "URL",
"value": "http://i.stack.imgur.com/G1dzB.png"
},
{
"type": "BYTES",
"value": "962B"
},
{
"type": "PERCENTAGE",
"value": "50%"
}
]
}
}
]
}
]
},
"PrioritizeVisibleContent": {
"localizedRuleName": "Prioritize visible content",
"ruleImpact": 2.0,
"urlBlocks": [
{
"header": {
"format": "Your page requires additional network round trips to render the above-the-fold content. For best performance, reduce the amount of HTML needed to render above-the-fold content."
}
},
{
"header": {
"format": "The entire HTML response was not sufficient to render the above-the-fold content. This usually indicates that additional resources, loaded after HTML parsing, were required to render above-the-fold content. Prioritize visible content that is needed for rendering above-the-fold by including it directly in the HTML response.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/speed/docs/insights/PrioritizeVisibleContent"
}
]
},
"urls": [
{
"result": {
"format": "Only about $1 of the final above-the-fold content could be rendered with the full HTML response $2.",
"args": [
{
"type": "PERCENTAGE",
"value": "26%"
},
{
"type": "SNAPSHOT_RECT",
"value": "snapshot:5"
}
]
}
}
]
}
]
}
}
},
"version": {
"major": 1,
"minor": 15
},
"screenshot": {
"data": "***************8This is the data i need!!*********",
"height": 240,
"mime_type": "image/jpeg",
"width": 320
}
}
You set the assoc Parameter in json_decode on true, so it will return an array!
You just have to delete true like this:
$jsonData = json_decode($response);
$testt = $jsonData->screenshot->data;
Of course you can change true to false aswell:
$jsonData = json_decode($response, false);
$testt = $jsonData->screenshot->data;
More information about this in the PHP-Manual for json_decode
use it like
$jsonData = json_decode($aa, true);
echo $jsonData['screenshot']['data'];
working code
First, there is an error in your JSON on line 11 that stops json_deocde() returning a valid array (you should remove the trailing comma):
"numberStaticResources": 22,
Second, you are getting an array from json_decode() so you need to use the correct syntax:
$jsonData = json_decode($response, true);
$testt = $jsonData['screenshot']['data'];

Verify one layer only

I want to verify a variable holding json only has one level simple format. Can someone provide an example where only one level is verified - not a multi-level verification?
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
isValidOnlayer($json); // True
$json = '{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}'
isValidOnlayer($json); // False
?>
You can use this as a result of your function:
count(array_filter(json_decode($json, 1), 'is_array'))
$tmp = json_decode($json, true, 2); // depth=2, the array "itself" is level 1, its elements are level 2
if $tmp is null an error occurred. In case the depth limit was the problem json_last_error() will return JSON_ERROR_DEPTH

Categories