PHP - remove HTML-attributes from string in JSON - php

I have a JSON-response from embed.ly which I get in my PHP-script like this:
// jSON URL which should be requested
$json_url = 'http://api.embed.ly/1/oembed?key=hidden&url='.$_POST['url'];
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
My problem is that I want the responses from embed.ly embedded in my responsive layout, but embed.ly-responses of videos include with & height attributes:
{"provider_url": "http://www.youtube.com/", "description": "Markus Eisenrings Stromboli electric car on swiss television broadcast. See www.stromboli.ch for more information.", "title": "Stromboli Electric Car", "url": "http://www.youtube.com/watch?v=TJCZnpHuFS8", "author_name": "hangflug", "height": 360, "thumbnail_width": 480, "width": 640, "html": "<iframe width=\"640\" height=\"360\" src=\"http://www.youtube.com/embed/TJCZnpHuFS8?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>", "author_url": "http://www.youtube.com/user/hangflug", "version": "1.0", "provider_name": "YouTube", "thumbnail_url": "http://i1.ytimg.com/vi/TJCZnpHuFS8/hqdefault.jpg", "type": "video", "thumbnail_height": 360}
I tried removing all width & height-attributes from that JSON-string like this:
$result = json_encode(preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i', '<$1$4$7>', json_decode($result)));
However, this is giving me a PHP-error.
Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/projectname/ajax.php on line 22
Any ideas?

Can't you just do this:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$result = json_encode($arr);
UPDATE: For your specific example:
$arr = json_decode($result, true);
unset($arr["height"], $arr["width"]);
$arr_temp = explode(' ', $arr["html"]);
foreach ($arr_temp as $i => $val) {
if ((substr($val, 0, 7) != "height=") && (substr($val, 0, 6) != "width="))
$arr_html[] = $val;
}
$arr["html"] = implode(' ', $arr_html);
$json_result = json_encode($arr);
PHP Sandbox

finally got it to work with help form here like this:
$arr = json_decode($result, true);
foreach ($arr as $key => & $val) {
if($key=='html'){
$html = preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i','<$1$4$7>', $arr['html']);
$arr[$key] = $html;
}
}
$result = json_encode($arr);

Related

execute php echo as parameter value

I have below code & I am generating tracking_id values manually & its working fine :
<?php
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Result :
{"response":[{"tracking_id":"1234",}],
Now i need to create tracking_id dynamically.... so i tried like below :
"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",
I got below Result :
{"response":[{"tracking_id":" = 'DOCC'. mt_rand(0000000001,9999999999); echo ;","
But i should get some random number as tracking_id....
Means php code inside parameter is not working....
As your require 10 digit random number:
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(1, 9);
}
return $result;
}
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";
Refactor your code:
$r = 'DOCC'. mt_rand(0000000001,9999999999);
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => $r,
];
Just replace $data array with the following.
$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'. mt_rand(0000000001,9999999999),
];

Php Curl to Json

I can get data from a website with CURL.
I want to convert this data to json.
my code:
<?php
function Curlconnect($start,$end,$website) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website = curl_exec($ch);
preg_match_all('#'.$start.'(.*?)'.$end.'#si',$website,$ver);
return $ver[1];
curl_close($ch);
}
function nt($start,$bit,$data,$a) {
preg_match_all('#'.$start.'(.*?)'.$bit.'#si',$data,$ver);
return $ver[1];
}
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
echo $printdata[0]. '<br />';
}
?>
Output:
1
27
32
66
94
I want to convert this data to json like that:
{
"data":{
"numbers":
[
"1",
"27",
"32",
"66",
"94",
]
}
}
How Can I do that?
Thank you very much.
Please try this
$url = 'http://www.url.com';
$getdata = Curlconnect('<h4','h4>',$url);
$jsonData = ["data"];
$jsonData["numbers"] = [];
for ($a=0; $a<count($getdata); $a++) {
$printdata = nt('>','</',$getdata[$a],$a);
$jsonData["numbers"][] = $printdata[0];
}
echo json_encode($jsonData);

Get JSON from URL by PHP

I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);

How Php To Json converted?

We can convert php code how to json format?
I may have not accurately PHP coding I am beginner to learn about it because I'm new . I'll integrated into Android application.
I also draw pictures about how the information ?
for example, I want to do something like this: http://mikepenz.com/android/unsplash/pictures
<?php
// don't forget to change 'username' to your actual tumblr name
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
// Tumblr JSON doesn't come in standard form, some str replace needed
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
// parameter 'true' is necessary for output as PHP array
$value = json_decode($input, true);
$content = $value['posts'];
// the number of items you want to display
$item = 98988;
// Tumblr provides various photo size, this case will choose the 75x75 square one
$type = 'photo-url-1280';
?>
{
"limit": null,
"offset": 0,
"count": 2442,
"total": 2442,
"data": [
<?php
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
echo '
{
"id": '.$i.';
"author": "Paul Jarvis",
"image_src": "' . $content[$i][$type] . '",
"color": "#7F7873",
"date": "2015-01-21 19:20:00",
"modified_date": "2014-09-01 22:36:53",
"width": 2500,
"height": 1667,
"ratio": 1.4997000694275,
"featured": 1,
"temp_id": 1
}';
$string = rtrim($item, ', ');
}
}
?>
]}
Try using the json_encode() function
<?php
$request = 'http://walltumbler.tumblr.com/api/read/json';
$ci = curl_init($request);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
$input = curl_exec($ci);
$input = str_replace('var tumblr_api_read = ','',$input);
$input = str_replace(';','',$input);
$value = json_decode($input, true);
$content = $value['posts'];
$item = 98988;
$type = 'photo-url-1280';
$photos_array = array();
for ($i=0;$i<=$item;$i++) {
if ($content[$i]['type'] == 'photo') {
$photos_array[] = array(
'id' => $i,
'author' => 'Paul Jarvis',
// Continue with all your values...
);
}
}
$json_data = array(
'limit' => null,
'offset' => 0,
'count' => 2442,
'total' => 2442,
'data' => $photos_array
);
// Then use json_encode to get your json data...
echo json_encode( $json_data );
Hope it helps

Array of Freebase MIDs and sending multiple queries to freebase

I want to loop through the MySQL results which is an array of Freebase MIDs and I want the output to be the names of the Freebase article!
Here's my code:
$query = "SELECT `mid` FROM `items`";
$result = mysql_query($query);
$count = 1;
while ($row = mysql_fetch_array($result)) {
$mid = $row['mid'];
$simple_query = array('name'=> null, 'mid'=>$mid);
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
$count++;
}
$jsonquerystr = json_encode($query_array);
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array
foreach($resultarray as $name){
echo "$name<br>";
}
error:
{ "code": "/api/status/error", "messages": [ { "code": "/api/status/error", "message": "'list' object has no attribute 'get'" } ], "status": "500 Internal Error", "transaction_id": "cache;cache04.p01.sjc1:8101;2012-05-14T07:31:39Z;0079" }
Your $query_array should just be an associative array of queries by name rather than an array of associative arrays. So instead of this:
$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );
..it should look something like this:
$q_array = array('query'=>$simple_query);
$query_array['q'.$count] = $q_array;
However, that code is using the old Freebase API which is about to be deprecated. A better way to do this in the new API would be to structure it all as one query like this:
[{
"mid": null,
"name": null,
"topics:mid|=":[
"/m/045c7b",
"/m/0d6lp",
"/m/021ympy",
...
]
}]
This lets you pass in an array of MIDs and get back a name for each one. The URL to fetch this from the new API should look something like this:
https://www.googleapis.com/freebase/v1/mqlread/?query=[{...}]

Categories