2013-02-16 148 views
0

我從embed.ly一個JSON響應,我得到我的PHP腳本是這樣的:PHP - 從字符串中刪除HTML的屬性在JSON

// 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 

我的問題是,我想從響應embed.ly嵌在我響應佈局,但視頻embed.ly-反應包括與& height屬性:

{"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} 

我試着刪除了所有寬度&從JSON字符串這樣的高度屬性:

$result = json_encode(preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i', '<$1$4$7>', json_decode($result))); 

但是,這給了我一個PHP錯誤。

Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/projectname/ajax.php on line 22 

任何想法?

+0

什麼錯誤它給? – martriay 2013-02-16 18:54:38

+0

你會得到什麼錯誤? – desbest 2013-02-16 18:58:59

+0

對不起,在 – 2013-02-16 19:00:12

回答

0

你就不能這樣做:

$arr = json_decode($result, true); 
unset($arr["height"], $arr["width"]); 
$result = json_encode($arr); 

UPDATE:爲了您的具體的例子:

$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

+0

無法在我的機器上運行...? – 2013-02-16 19:19:58

+0

@RaphaelJeger - 最後一行發生錯誤。 'json_encode($ result);'應該是'json_encode($ arr);' – Stefan 2013-02-16 21:54:05

+0

是的,我注意到,但它仍然不起作用... – 2013-02-17 06:45:46

0

終於得到它在這裏這樣有助於形成工作:

$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);