Foreach Urls JSON解码

时间:2017-08-30 19:25:32

标签: php json

$urlsDB是一个包含JSON的变量。

print_r($urlsDB );

输出:

[\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\",\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"]

如何正确使用foreach创建json_decode

   <?php
    $urls = json_decode($urlsDB , true);

    if ($urls != '' ) { 

            foreach ($urls as $url) {
    ?>
    <img src="<?php echo $url;?>"  class="img-responsive img-thumbnail " />

    <?php
     }
    }

    ?>

Var_dump($urls);返回空。

2 个答案:

答案 0 :(得分:1)

您获得了无效的JSON。您已在开头和结尾转义了引号。这是有效的:

["http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png","http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg"]

也许您在处理数据库之前应用了一些过滤器?

这应该有效:

<?php
$a = '["http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png","http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg"]
';
$urls = json_decode($a, true);
if (count($urls) > 0) {
    foreach ($urls as $url) {
    ?>
        <img src="<?php echo $url;?>"  class="img-responsive img-thumbnail " />
    <?php
    }
}

你不应该htmlspecialchars() JSON编码的字符串。这将转义引号,使JSON对象无效。你应该做的是htmlspecialchars()数组中的每个元素,最好是在显示时,而不是在保存时(阅读here)。

答案 1 :(得分:0)

尝试在json_decode()

之前删除斜杠
$input = '[\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\",\"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"]';

$json = json_decode(stripslashes($input),true);

var_dump($json)的输出给了我以下

array(2) {
    [0]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/LOGO-SEG-2.png"
    [1]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/algoritims.jpg"
}

试一试here

编辑添加:

原始字符串实际上是json数组的字符串表示形式,而不是对象,因为它没有键。我在每个元素上使用url键的对象上尝试了相同的修复,这就是结果。

$input = '[{\"url\" : \"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/LOGO-SEG-2.png\"},{\"url\" : \"http:\\/\\/localhost\\/theme\\/wp-content\\/uploads\\/2017\\/08\\/algoritims.jpg\"}]';

$json = json_decode(stripslashes($input),true);

输出:

array(2) {
    [0]=> array(1) {
        ["url"]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/LOGO-SEG-2.png"
    }
    [1]=> array(1) {
        ["url"]=> string(64) "http://localhost/theme/wp-content/uploads/2017/08/algoritims.jpg"
    }
}

此外,\" 字符串文字中的有效json字符。仅当使用"声明变量时才有效(例如:$encoded = "{\"some value\"}";)。

echo var_dump(json_decode('{\"myKey\": \"myValue\"}', true)); // output: NULL

试试live

相关问题