Extract JSON Array from data - php

I am requesting data from another website and expecting a clean json array in return.
However I am getting this instead:
<pre></pre>{"Status":"Success","Result":1}
which won't parse with json_decode();.
How do I extract the JSON array out of this data so I can parse it?
Note: I am not in control of the code I am requesting the data from.

try this
$output_array = array();
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
preg_match("/{.*}/", $badstr, $output_array);
in $output_array[0] you have your json string.

Assuming that <pre></pre> is constant, then just a simple substring operation:
$badstr = '<pre></pre>{"Status":"Success","Result":1}';
$goodstr = substr($badstr, 11);
But you really should yell at the server admins for sending out bad json in the first place. There's no excuse for this kind of thing. It's probably some debug code they forgot to take out.

If you want it to work both now, and once the issue will be fixed, you can do this:
$result = '<pre></pre>{"Status":"Success","Result":1}';
if (strpos($result ,'<pre>') !== false)
{
$array = json_decode(substr($result , 11));
}
else
{
$array = json_decode($result);
}

Only remove <pre></pre>, only if it's the first thing:
$response = preg_replace('#^<pre></pre>#', '', $response);

How about simply string replace?
Like so:
$json_string = '<pre></pre>{"Status":"Success","Result":1}';
$json = str_replace("<pre></pre>", "", $json_string);
echo $json;
Output:
{"Status":"Success","Result":1}

If you don't expect any html tags in your output, you can also use strip_tags():
$not_json = '<pre></pre>{"Status":"Success","Result":1}';
$json_string = strip_tags($json);
$result = json_decode($json_string);

Related

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

PHP: Extract specific word after specific word in a string?

I have a string that looks like this:
{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}
i only need the value for the country_name from that string.
so I tried this:
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
if (preg_match('#^country_name: ([^\s]+)#m', $country, $match)) {
$result = $match[1];
}
echo $result;
but there is nothing being echoed in the $result
Could someone please advise on this issue?
$country = json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}');
echo $country->country_name;
What you have there is a JSON string.
JSON stands for JavaScript Object Notation.
PHP can decode it into an Array or Object via json_decode($string, FALSE);
The 2nd parameter by default is FALSE, which means it will convert the string into an object, which you can then access as I showed you above.
If for some reason you don't want to use JSON you can give the following a try. Note that using JSON is the recommended way doing this task.
$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$temp = explode('"country_name":', $country); //Explode initial string
$temp_country = explode(',', $temp[1]); //Get only country name
$country_name = str_replace('"', ' ', $temp_country[0]); //Remove double quotes
echo $country_name;
Result:
Ireland
Try this:
<?php
$country=json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}')
$result=$country->country_name;
echo $result;
?>
This looks like a json string. Read more about JSON.
Use it like this:
$foo = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$bar = json_decode($foo, true);
echo $bar['country_name'];
This can be used with any key from that string (eg ip, city)
More about json_decode.

How to remove the <br> tag from an array in PHP?

I've an array titled $error_msg as follows:
Please select at least 1 question issue<br>This question has been already reported<br>
Now I'm converting this array into json format by using following code:
$response_data = array();
$response_data['que_issue_error'] = 'yes';
$response_data['error_msg'] = $error_msg['error_msgs'];
$response_data = json_encode($error_msg);
echo $response_data;
die;
After echo the output is as follows:
{"que_issue_error":"yes","error_msg":"Please select at least 1 question issue<br>This question has been already reported<br>"}
Actually I want to make the track workable but what's happening is the tag is printing as it is. Can anyone help me how to correct this error? Thanks in advance.
You can use;
$response_data['error_msg'] = preg_replace("/<br\W*?\/>/", "", $error_msg['error_msgs']);
Try this:
// Replace tag for blank space
$response_data['error_msg'] = preg_replace('/<.+>/', ' ',$error_msg['error_msgs']);
OR simple strip tags (for any html tags)
$response_data['error_msg'] = strip_tags($error_msg['error_msgs']);
If you simply want to remove all HTML tags, you can use the strip_tags function
$response_data['error_msg'] = strip_tags($error_msg['error_msgs']);
You can use str_replace:
$data = // your data // $response_data
$data = str_replace("<br>", "", $data);
$data = str_replace("<br />", "", $data);
To remove all html tags, use strip_tags:
$data = strip_tags($data);
You can also use regular expressions: use this regex to remove empty br
Try
$data = // your data
$pattern = "/<br[^>]*><\\/br[^>]*>/";
$data = preg_replace($pattern, '', $data);
To replace all empty html tags:
$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/";
I don't exactly what you're trying to do but you can try this:
str_replace("<br>", "\n", $data); //That depends on where you are tring to display the output
It'll maybe solve your problem and maintain the break line, or if it's not work
you can just take the break line off like this:
str_replace("<br>", "", $data);
Hope it helps!

getting value using explode

I am trying to parse following string...
IN.Tags.Share({"count":180,"url":"http://domain.org"}
is my following approach correct to get the value of count?
$str = 'IN.Tags.Share({"count":180,"url":"http://domain.org"}';
$data = explode(':', $str);
$val = explode(',', $data[1]);
return $val[0];
Or is there any better way to handling this type of strings? I think it could be done using regex as well.
thanks.
If course I'm not sure if your format will be constant, but part of your string looks like JSON. If always like this, you could do:
$str = str_replace('IN.Tags.Share(', '', $str);
$values = json_decode($str);
echo $values->count;
I would suggest pulling out the JSON by applying this regex to the string: IN\.Tags\.Share\((.*)\. Pull out the first group, and use json_decode: http://php.net/manual/en/function.json-decode.php
That way, you can directly access the data. It will support complex data structures as well.

Best way to parse this response into an associative array?

Below is the response I'm getting after posting to an API.... I don't think parse_url is going to cut it. Are there any built in PHP functions or better ways to turn this into an array? This is the output of var_dump
sting(163) "response=3&responsetext=Duplicate transaction REFID:115545335&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300&processor_id="
Use parse_str() with the optional $arr parameter.
Parses str as if it were the query string passed via a URL
You are looking for parse_str.
It turns a query string into an associative array.
I propose :
$elements = explode('&', $input);
$data = array();
foreach($elements as $e) {
$d = explode('=', $e);
$data[$d[0]] = isset($d[1]) ? $d[1] : '';
}
But maybe there is a better way.

Categories