SimpleXML - echo / print_r 返回不同的值
我正在尝试使用 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 语句等值。为什么这些不同?
I am trying to convert some xml into a json object using PHP.
This should be working, yet for some bizarre reason it is failing.
Could someone provide some input.
// 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++;
}
This code returns the following.
{"background":{"0":"000033"},
"image":"0":"0210e849f02646e2f5c08738716ce7e8b3c1169112790078351021245495.jpg"},
"caption": {"0":"Frog"}}
print_r($image['bgColor']); shows 'SimpleXMLElement Object ( [0] => 000033 )'
echo $image['bgColor']; shows '000033'
How do I parse values like the echo statement instead of the print_r statement. Why are these different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为这些变量内部不是字符串,而是
SimpleXMLElement
类型对象,在通过echo
输出时会转换为字符串。要在其他地方使用这些值,我通常会进行显式转换:
有关将 simplexml 元素转换为字符串的规范问题如下:
Because these variables are not strings internally, but
SimpleXMLElement
type objects that get converted into strings when output byecho
.To use the values elsewhere,I usually do an explicit cast:
A canonical question regarding casting a simplexml element into a string is here: