SimpleXML-ECHO/print_r返回不同值

2022-04-13 00:00:00 php simplexml

我正在尝试使用PHP将一些XML转换为JSON对象。

这应该是有效的,但由于某种奇怪的原因,它却失败了。

有人能提供一些输入吗?

// Loop Through images and return the right one.
$i = 1;
foreach($page->image as $image) {
    if ($i == $_GET['id']) {
         echo json_encode(array(
            'background' => $image['bgColor'],
            'image' => $image['source'],
            'caption' => $image['caption']
         ));
    }
    $i++;
}

此代码返回以下内容。

{"background":{"0":"000033"},
 "image":"0":"0210e849f02646e2f5c08738716ce7e8b3c1169112790078351021245495.jpg"},
 "caption":   {"0":"Frog"}}

print_r($image['bgColor']); shows 'SimpleXMLElement Object ( [0] => 000033 )'

echo $image['bgColor']; shows '000033'
如何解析像ECHO语句这样的值,而不是print_r语句。为什么这些不同?


解决方案

为什么这些不同

因为这些变量在内部不是字符串,而是SimpleXMLElement类型的对象,这些对象在echo输出时被转换为字符串。

要在其他地方使用这些值,我通常会执行显式强制转换:

$bg_color = (string) $image['bgColor'];

以下是有关将简单exml元素转换为字符串的规范问题:

  • Forcing a SimpleXML Object to a string, regardless of context

相关文章