Json Decode returning NULL - php

I am trying to decode json into array in PHP.But My json is like
string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" "
string within a string!!
How to convert it into array.

This looks like you're trying to decode (or trying to output) the data with var_dump(). That isn't the function you require; what you require is json_decode():
$data = json_decode($json);
If that isn't the issue, and you're actually receiving the data as above then you'll have to strip it out - most likely using a regex like the following:
$s = 'string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" "';
preg_match('/\{(.*)\}/', $s, $matches);
print_r($matches);
Which would return your json:
Array
(
[0] => {"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}
[1] => "id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"
)
Thus allowing you to decode it properly within $matches.
Regex is a beast to me so I'll try explain as best as possible what the expression is doing:
\{ matches the first open {
(.*) matches any character inbetween
\} matches the closing }

Related

Trim Text From String PHP

I want remove unnecessary text from my string variable. I have variable like $from which contains value like 123456#blog.com. I want only 123456 from it. I have checked some example for trim but does not getting proper idea for do it. Let me know if someone can help me for do it. Thanks
You can split the string on the # symbol like so:
$str = "123456#blog.com";
// here you split your string into pieces before and after #
$pieces = explode("#",$str);
// here you echo your first piece
echo $pieces['0'];
Demo
You can use explode() for splitting the string.
Syntax:
explode('separator', string);
$result= explode("#", '123456#blog.com');
print_r($result);
Output:
Array
(
[0] => 123456
[1] => blog.com
)

Obtaining PHP regex matches but unable to do anything with them

I have some PHP code that accepts an uploaded file from an HTML form then reads through it using regex to look for specific lines (in the case below, those with "Track Number" followed by an integer).
The file is an XML file that looks like this normally...
<key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer>
But when PHP reads it in it gets rid of the XML tags for some reason, leaving me with just...
Disc Number2
Disc Count2
Track Number1
The file has to be XML, and I don't want to use SimpleXML cause that's a whole other headache. The regex matches the integers like I want it to (I can print them out "0","1","2"...) but of course they're returned as strings in $matches, and it seems I'm unable to make use of these strings. I need to check if the integer is between 0 and 9 but I um unable to do this no matter what I try.
Using intval() or (int) to first convert the matches to integers always returns 0 even though the given string contains only integers. And using in_array to compare the integer to an array of 0-9 as strings always returns false as well for some reason. Here's the trouble code...
$myFile = file($myFileTmp, FILE_IGNORE_NEW_LINES);
$numLines = count($myFile) - 1;
$matches = array();
$nums = array('0','1','2','3','4','5','6','7','8','9');
for ($i=0; $i < $numLines; $i++) {
$line = trim($myFile[$i]);
$numberMatch = preg_match('/Track Number(.*)/', $line, $matches); // if I try matching integers specifically it doesn't return a match at all, only if I do it like this - it gives me the track number I want but I can't do anything with it
if ($numberMatch == 1 and ctype_space($matches[1]) == False) {
$number = trim($matches[1]); // string containing an integer only
echo(intval($number)); // conversion doesn't work - returns 0 regardless
if (in_array($number,$nums)===True) { // searching in array doesn't work - returns FALSE regardless
$number = "0" . $number;
}
}
}
I've tried type checking, double quotes, single quotes, trimming whitespace, UTF8 encoding, === operator, regex matching numbers specifically with (\d+) (which doesn't return a match at all)...what else could it possibly be? When I try these things with regular strings it works fine, but the regex is messing everything up here. I'm about to give up on this app entirely, please save me.
Why is SimpleXML not an option? Consider the following code:
$str = "<container><key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer></container>";
$xml = simplexml_load_string($str);
foreach ($xml->key as $k) {
// do sth. here with it
}
You should read RegEx match open tags except XHTML self-contained tags -- while doesn't exactly match your use case it has good reasons why one should use something besides straight up regexp matching for your use case.
Assuming that files only contain a single Track Number you can simplify what you're doing a lot. See the following:
test.xml
<key>Disc Number</key><integer>2</integer>
<key>Disc Count</key><integer>2</integer>
<key>Track Number</key><integer>1</integer>
test.php
<?php
$contents = file_get_contents('test.xml');
$result = preg_match_all("/<key>Track Number<\/key><integer>(\d)<\/integer>/", $contents, $matches);
if ($result > 0) {
print_r($matches);
$trackNumber = (int) $matches[1][0];
print gettype($trackNumber) . " - " . $trackNumber;
}
Result
$ php -f test.php
Array
(
[0] => Array
(
[0] => <key>Track Number</key><integer>1</integer>
)
[1] => Array
(
[0] => 1
)
)
integer - 1%
As you can see, there is no need to iterate through the files line by line when using preg_match_all. The matching here is very specific so you don't have to do extra checks for whitespace or validate that it's a number. Which you're doing against a string value currently.

Converting array to JSON string when array already contains JSON strings

I have an array that contains a JSON string.
Array
(
[0] => Array
(
[name] => Original
[nutrients] => {"calories":{"value":2500,"operator":2},"protein":{"value":500,"operator":1},"carbs":{"value":200,"operator":0},"fat":{"value":50,"operator":0},"sugar":{"value":1,"operator":2}}
)
[1] => Array
(
[name] => Rest
[nutrients] => {"calories":{"value":5000,"operator":2},"sugar":{"value":10,"operator":2}}
)
)
I want to turn the whole array into a JSON string
echo json_encode($array);
But this throws a \ in front of all quotes
[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]
This problem comes about because the nutrients value is already a JSON string.
How can I convert an array into a JSON string when it already contains JSON strings, while having no slashes in front of the quotes?
Use json_decode to convert 'nutrients' to array.
foreach($array as &$a){
$a['nutrients'] = json_decode($a['nutrients']);
}
Then
echo json_encode($array);
How can I convert an array into a JSON string when it already contains JSON strings, while having no slashes in front of the quotes?
If you want to preserve the JSON values as strings; then, you can't, and you shouldn't be able to!
If your array already contains some JSON values (in which they'll have some quotation marks: ") and you want to encode that array into a JSON string, then the quotation marks must be properly escaped, what you get correctly; otherwise, the entire JSON string will be corrupt because of miss-quotation-mark matches.
That's because the " has a special meaning in JSON, but the \" means the "double quotation mark character" not the special token of "; for example, removing the backslashes from the valid JSON string causes some syntax errors for sure:
$json = '[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]';
$json_noBackslashes = str_replace('\\', '', $json);
$json_decoded = json_decode($json_noBackslashes);
echo json_last_error_msg(); // Syntax error
You should be able to json_decode the json data first, then put it back to the original array. After that, you can encode the whole array again to get the desired output.
foreach ($data as $datum) {
$data['nutrients'] = json_decode($data['nutrients']);
}
json_encode($data);

How to check single byte katakana in a string

Iam working with Double byte japaneese character website, i need to check the user enter a single byte katakana.Site developed in php platform.
This is the preg match that i used for checking
'/[\x{3040}-\x{309F}]/u'
I'm not 100% sure if this the test string I use is legal $string. I'll remove the answer (or try to update it) if it works out different. As the string is manual input (escaped the backslash initially), instead of raw;
$string = "\\xe3\\x80\\x85"; // RAW input might still be '\xe3\x80\x85' here
$result = preg_match_all("/\\\\xe3\\\\x8[0-3]\\\\x[8-9a-b][0-9a-f]/u", $string, $matches);
echo $string;
echo '<pre>';
print_r($matches);
echo '</pre>';
This prints out;
\xe3\x80\x85
Array
(
[0] => Array
(
[0] => \xe3\x80\x85
)
)
Thus; 々

Parse JavaScript from remote server using curl

I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array

Categories