I have this simple statement to call a JSON response. It was working until recently I found out it stopped working. Not sure why its not working. Here is my code. Its very simple.
//Here is the response from the API
{"country":"US","state":"NY","city":"GLEN COVE"}
$zip = "11542";
$url = "http://ziptasticapi.com/".$zip;
$info = file_get_contents($url);
$info = json_decode($info);
$cityname = $info->city;
$statename = $info->state;
Not sure why its not picking up the data at the end. I even tried changing it to json_decode($info,true) and changing it to $info['city'].
Related
I'm using Guzzle with Laravel to get an object from external API with a HTTP. The API return XML Object similar to this (https://www.w3schools.com/php/note.xml)
I need to check one value of the response body. Here is my code:
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
echo $stringBody;
which is working fine, I mean it display the body as below picture
but I couldn't get one value?
I tried different methods but non of them is working!
for example, this way:
$result = starts_with($stringBody, 'Tove');
or
splitName = explode(' ', $res->getBody());
$first_name = $splitName[0];
echo $first_name;
non is working? I think it consider the body text empty ?
I tried using json_decode but it doesn't work or not supported anymore.
Any idea?
Thanks
What you get from response is xml content. Due to browser compatibility with XML you see only text. You just need SimpleXML class of php for get content as per XML node. Here is sample code
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
$stringBody = (string) $res->getBody()->getContents();
$xml = simplexml_load_string($stringBody);
echo $xml->to;
Hope this help you.
I have a SPA (react) that is uses PHP calls to connect to a MongoDB.
Works great.
However, due to 'rules' I need to serve the javascript files from a different server -- a server that supports neither MongoDB nor MongoDB php client. Let's call this server, SERVER_A.
Let's call the server hosting the MongoDB PHP client and the MongoDB, SERVER_B. ('B' for 'backend'... :) )
The solution, I believe, was to build a php 'middleman' on SERVER_A that simply passes data on to SERVER_B. Research shows me that file_get_contents is the tool for this.
So I take my original known-working PHP file, I put it on SERVER_B and rename it to "mongoPatch_backend.php".
<?php
$user = "xxxx";
$pwd = 'xxx';
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$manager = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
[$needleKey => $needle],
['$set' => $value],
['multi' => false, 'upsert' => true]
);
$results = $manager->executeBulkWrite('sedwe.users', $bulk);
var_dump($results);
?>
On SERVER_A I then make a new file, dbPatch.php, like so:
<?php
$API = "https://SERVER_B/php/mongoPatch_backend.php?";
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$postData = "needleKey=".urlencode($needleKey);
$postData .= "&needle=".urlencode($needle);
$postData .= "&newData=".urlencode($newData);
// echo $API.$postData;
$data = file_get_contents($API.$postData);
echo $data;
?>
But when I call it, I get nothing echo'd back out of $data.
Any idea why? Remember, the exact same call directly to mongoPatch_backend.php works just fine (but it's a CORS call, so it's not a valid option).
So here is what I've tried:
First, to ensure my AJAX call was still working, I spit out the response to the console. I get nothing.
So I changed the last line of the middleman (dbPatch.php) to echo "Hello World" instead of echo $data and received "Hello World" on the console as expected.
Next, I then changed the last line of my middleman (dbPatch.php) back to echo $data and tried reducing the 'backend' to a simple <?php echo "Hello Back World"; ?> and got nothing on the console.
Next, I go to https://SERVER_B/php/mongoPatch_backend.php in a browser ... and I'm greeted with "Hello Back World" as expected in the browser.
... which leads me to believe something is up with the transferring of info from server to server. Logical call, eh?
Unfortunately, when I try the same thing with just a 'fetch' command, it works perfectly fine:
Here is my 'middleman' (dbFetch.php) script on SERVER_A:
<?php
$API = "https://SERVER_B/php/mongoFetch_backend.php?";
$collection = $_REQUEST['collection'];
$postData = "collection=".urlencode($collection);
$needleID = $_REQUEST['needleID'];
$postData .= "&needleID=".urlencode($needleID);
$data = file_get_contents($API.$postData);
echo $data;
?>
And this is the file on the backend, SERVER_B:
<?php
$user = "xxxx";
$pwd = 'xxxx';
$filter = [];
if (isset($_REQUEST['needleID'])) {
$needleID = $_REQUEST['needleID'];
$filter = ['id'=> $needleID];
}
if (isset($_REQUEST['collection'])) {
$collection = $_REQUEST['collection'];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
$rows = $connection->executeQuery("db_name.$collection", $query);
// Convert rows to Array and send result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
Huzzah, this works! ... and it's also proof there doesn't appear to be a problem with the server-to-server communication.
So back to ground zero.
I then go with a very simple newData value -- shorter, but same general layout - stringified json. It works! The data ends up in the database.
So I'm forced to think something is wrong with the data in newData (which is only a few hundred lines of stringified JSON made like this: encodeURIComponent(JSON.stringify(newData)). But, this bears repeating: this works if I skip the middleman.
... and that puts me at a loss. PHP isn't something I understand well... can you help?
EDIT to answer comment:
When I call mongoPatch_backend.php directly on SERVER_B it works (as stated above). I had it echo the $newData and it spits out a stringified JSON version of the variable (not URLencoded).
When I call dbPatch.php, it does not give me anything that was passed back from mongoPatch_backend.
As I said in the OP, if I modify mongoPatch_backend.php to do nothing other than echo "hellow world" I am still unable to log it to console when calling it via the above dbPatch.php file.
EDIT: I also tried putting the two PHP files on the same server and am getting the same results. (ie: both the dbPatch.php and mongoPatch.php files are in the same directory on the same server)
EDIT2: I have done a var_dump from the middleman and I get standard-looking human-readable stringified text back.
I do the same var_dump($_REQUEST['newData']); in the backend file and I get nothing back.
I have a C# client, its send a json to my php server.
There is the json string:
{"data":[{"name":"1"}]}
Its a valid json. When i try it in PHP Sandbox its works good
$ad = '{"data":[{"name":"1"}]}';
$contents = utf8_encode($ad );
$results = json_decode($contents);
var_dump($results->data);
But,when i try in laravel 5.1, its not work good.
$response = $connection -> getData();
// return $response; (Its equal : {"data":[{"name":"1"}]} )
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data); // Error Trying to get property of non-object
I hope someone can help me.
Thanks!
Based on the comments, it looks like the socket_read() in the getData() method is reading 1 character at a time, and then concatenating each NUL terminated character into a response string. json_decoded() is choking on all the extra NUL characters.
You can either update your logic in the getData() method so it is not doing this, or you can run a str_replace on the results:
$response = $connection -> getData();
// get rid of the extra NULs
$response = str_replace(chr(0), '', $response);
$contents = utf8_encode($response);
$results = json_decode($contents);
dd($results->data);
I've got a really weird problem and I can't figure out why.
The situation is quite simple. My Android app uploads JSON data to a php script on my server. Right now I am trying to parse the data.
This is the JSON-Array passed to the script (via httpPost.setEntity ()):
[{"friends_with_accepted":"false","friends_with_synced":"false","friends_with_second_id":"5","friends_with_first_id":"6"}]
This is the php script:
<?php
// array for JSON response
$response = array();
$json = file_get_contents ('php://input');
$jsonArray = json_decode ($json, true);
foreach ($jsonArray as $jsonObject) {
$firstId = $jsonObject['friends_with_first_id'];
$accepted = $jsonObject ['friends_with_accepted'];
$secondId = $jsonObject ['friends_with_second_id'];
$synced = $jsonObject ['friends_with_synced'];
echo "accepted: ".$accepted."synced: ".$synced;
} ?>
And this is the response I get from the script:
accepted: synced: false
Why is the "synced" property correctly passed, but not the "accepted" property??
I can't see the difference. Btw, firstId and secondId are parsed correctly as well.
Okay, i just found the problem:
Instead of
$accepted = $jsonObject ['friends_with_accepted'];
I deleted the space between jsonObject and the bracket
$accepted = $jsonObject['friends_with_accepted'];
I found that App Store API support additional information about application.
$keyword = $this->input->post('keyword');
$appstore_api = 'http://itunes.apple.com/search?country=US&entity=software&term='.$keyword;
$data = file_get_contents($appstore_api);
echo $data;
here is the PHP code that I wrote.
I get this result.
{ "resultCount":50, "results": [ {"kind":"software", "features":[], "supportedDevices":["all"], "isGameCenterEnabled":false, "artistViewUrl":"http://itunes.apple.com/us/artist/burbn-inc./id389801255?uo=4", "artworkUrl60":"http://a2.mzstatic.com/us/r1000/105/Purple/v4/f3/0e/e2/f30ee271-c564-ec21-02d6-d020bd2ff38b/Icon.png", "screenshotUrls":["http://a3.mzstatic.com/us/r1000/102/Purple/v4/2d/25/d3/2d25d348-74e9-8365-208c-45e64af73ed6/mzl.xnvocmpt.png", "http://a1.mzstatic.com/us/r1000/077/Purple/v4/04/18/b3/0418b375-c0c1-18c1-1aef-07555c99af46/mzl.pkthtqtv.png", "http://a2.mzstatic.com/us/r1000/069/Purple/v4/31/08/65/31086528-2f37-bca0-71f3-c3095e698f35/mza_8774562250786021670.png", "http://a3.mzstatic.com/us/r1000/091/Purple/v4/95/a2/65/95a265bb-b9f0-8732-9fe4-823ffbc9aba0/mza_5807950548098772841.png"], "ipadScreenshotUrls":[], "artworkUrl512":"http://a4.mzstatic.com/us/r1000/089/Purple/v4/44/76/7f/44767fb5-4cb2-25bf-5361-25138b8c2aeb/mzl.ntalagmr.png",
The question is that how can I extract the variable named "artworkUrl512" ?
I tried like this but failed.
$image_url = $data->results->artworkUrl512;
$image_url2 = $data['results']['artworkUrl512'];
Can you help me how to extract icon image url?
$data is json encoded. Use json_decode():
http://php.net/manual/en/function.json-decode.php
$data = json_decode($json, true);
echo $data['results'][0]['artworkUrl512'];