convert string (JS object format) to PHP object - php

How I can convert string from URL to PHP object ? I know that its not valid JSON format but I still don't know how to convert it properly.
The following code returns NULL:
$url = 'https://cdn.shopify.com/s/javascripts/currencies.js';
$decodedCurrencies = json_decode(file_get_contents($url));
var_dump($decodedCurrencies);

You may use regex to extract rates array and then decode it.
Something like this:
$url = 'https://cdn.shopify.com/s/javascripts/currencies.js';
$script = file_get_contents($url);
$matches = [];
preg_match('/.+(\{.+}).+/', $script, $matches);
$decodedCurrencies = json_decode($matches[1]);
var_dump($decodedCurrencies);
Output:
object(stdClass)#1 (179) {
["USD"]=>
float(1)
["EUR"]=>
float(1.1637)
["GBP"]=>
float(1.31291)
["CAD"]=>
float(0.778138)
["ARS"]=>
float(0.0566433)
["AUD"]=>
float(0.766026)
["BRL"]=>
float(0.303944)
["CLP"]=>
float(0.00157516)
...
}

Related

php regex doesn't seem to work as expected

String:
https://fakedomain.com/2017/07/01/the-string-i-want-to-get/
Code:
$url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
$out = [];
preg_match('\/\d{4}\/\d{2}\/\d{2}(.*)', $url, $out);
// At this point $out is empty...
// Also... I tried this (separately)
$keywords = preg_split("\/\d{4}\/\d{2}\/\d{2}(.*)", $url);
// also $keywords is empty...
I've tested the regex externally and it works. I want to split out the /the-string-i-want-to-get/ string. What am I doing wrong?
I would not use a regex. In this case it's better to use parse_url and some other helpers like trim and explode.
<?php
$url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
$parsed = parse_url($url);
$Xploded = explode('/',trim($parsed['path'],'/'));
print $Xploded[count($Xploded)-1];
// outputs: the-string-i-want-to-get
There's a function for that:
echo basename($url);
preg_split
Split string by a regular expression. Split the given string by a regular expression.
Your $url will be split by the dates. That's not the way you need to do:
<?php
$url = 'https://fakedomain.com/2017/07/01/the-string-i-want-to-get/';
$out = [];
preg_match('/\/\d{4}\/\d{2}\/\d{2}(.*)/', $url, $out);
// See here...
var_dump($out);
You will get an array of two elements:
array(2) {
[0]=>
string(37) "/2017/07/01/the-string-i-want-to-get/"
[1]=>
string(26) "/the-string-i-want-to-get/"
}

Copying and adding JSON schema as array in PHP

I am trying to add a copy of a key and its content to the JSON file by using php.
$content = file_get_contents($_POST["content"]);
$decode = json_decode($content,true);
$version = $_POST["version"];
array_unshift($decode['versions'],$version );
$encode = json_encode($decode,true);
Let's say we want to add the version 1.2.2. This adds:
...["versions"]=> array(6) { [0]=> string(5) "1.2.2" ["1.2.1"]=> array(4) { ["project"]=> string(21)...
instead of creating a 1.2.2 key and its sub arrays.
Also tried:
array_unshift($decode['versions'][$version],$version );
without results either
If I undestand correctly, you can directly put the version inside your content like this :
$content = file_get_contents($_POST['content']);
$decode = json_decode($content, true);
$version = $_POST['version'];
$decode['version'] = $version;
$encode = json_encode($decode, true);

Decode JSON to PHP

I have a .txt file called 'test.txt' that is a JSON array like this:
[{"email":"chrono#gmail.com","createdate":"2016-03-23","source":"email"}]
I'm trying to use PHP to decode this JSON array so I can send my information over to my e-mail database for capture. I've created a PHP file with this code:
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
echo $json;
?>
For some reason, it's not echoing the decoded JSON when I visit my php page. Is there a reason for this and can anyone shed some light? Thanks!
You use echo to print scalar variables like
$x = 'Fred';
echo $x;
To print an array or object you use print_r() or var_dump()
$array = [1,2,3,4];
print_r($array);
As json_decode() takes a JSON string and converts it to a PHP array or object use print_r() for example.
Also if the json_decode() fails for any reason there is a function provided to print the error message.
<?php
$url = 'http://www.test.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
if ( json_last_error() !== JSON_ERROR_NONE ) {
echo json_last_error_msg();
exit;
}
You'll need to split that json string into two separate json strings (judging by the pastebin you've provided). Look for "][", break there, and try with any of the parts you end up with:
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}

JSON output for mapping data using json_decode() in php

I am attempting to write PHP code to interact with JSON output from Mapquest's Open API / Open Street Map service. I have listed it below. I have been using this code in my Drupal 6 implementation. This code returns no output. When I use it, json_last_error() outputs 0.
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
You can view the raw JSON output by following the URL. In this function I am expecting to get 1.257899 as my output. I have two questions:
(1) What can I call so I get items out of my array. For instance, how can I get the value represented in JSON "distance":26.923 out of the array?
(2) Is it possible am I running into a recursion limit issue that I've read about in the PHP Manual?
If you read the manual page for json_decode carefully, you'll notice there is a parameter (false by default) that you can pass to have it return an array rather than an object.
$obj = json_decode($json, true);
So:
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();
Remove the var_export function from json_decode.
You're trying to convert information about a string to json.
I was able to get the fuelUsed property this way
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}

remove string in json that contains value via jquery or php

I have json string, which is produced by server.php
[{"attr":{"id":"node_7","rel":"default"},"data":"doc.html","state":""},
{"attr":{"id":"node_8","rel":"folder"},"data":"New node","state":"closed"},
{"attr":{"id":"node_9","rel":"folder"},"data":"New node","state":""}]
How do I remove a full string that contains the value rel=default
This is the code I have for server.php.
require_once("config.php");
$jstree = new json_tree();
echo $jstree->{$_REQUEST["operation"]}($_REQUEST);
die();
Using PHP:
// convert json string to array
$json = json_decode($json_string);
// filter out items
$json = array_filter($json, function($item)
{
return $item->attr->rel != "default";
});
// convert back to string
$json_string = json_encode($json);
You can use data.items.splice(X, Y); to remove an element ;)

Categories