PHP - 从JSON中的字符串中删除HTML属性

时间:2013-02-16 18:51:53

标签: php json attributes replace

我有一个来自embed.ly的JSON响应,我在我的PHP脚本中得到如下:

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

我的问题是我希望将嵌入的响应嵌入到我的响应式布局中,但嵌入式视频的响应包括&高度属性:

{"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字符串的height-attributes如下:

$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

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

你不能这样做:

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

更新:对于您的具体示例:

$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

答案 1 :(得分: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);