如何替换PHP数组?

时间:2011-10-27 20:28:42

标签: php xml

我目前有这段代码。

<?php
$username = 'EMAIL ADDRESS';
$password = 'EMAIL ADDRESS';
$opts = array(
  'http' => array(
      'method'  => 'GET',
      'header'  => sprintf("Authorization: Basic %s\r\nUser-Agent: Foobar!", base64_encode($username.':'.$password))
  )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);
$xml =  new SimpleXMLElement(
    "https://mail.google.com/mail/feed/atom",
    null,
    true);
print_r($xml);
?>

运行PHP代码时,我得到以下结果

  

SimpleXMLElement对象([@attributes] =&gt;数组([版本] =&gt; 0.3)[标题] =&gt; Gmail - 电子邮件地址的收件箱[标语] =&gt; Gmail收件箱中的新邮件[fullcount] =&gt; 1 [link] =&gt; SimpleXMLElement对象([@attributes] =&gt;数组([rel] =&gt; alternate [href] =&gt; http://mail.google.com/mail [type] =&gt; text / html) )[modified] =&gt; 2011-10-27T20:12:38Z [entry] =&gt; SimpleXMLElement对象([title] =&gt; SUBJECT [link] =&gt; SimpleXMLElement对象([@attributes] =&gt;数组( [rel] =&gt; alternate [href] =&gt; LINK [type] =&gt; text / html))[modified] =&gt; 2011-10-26T15:45:11Z [已发布] =&gt; 2011-10- 26T15:45:11Z [id] =&gt; tag:gmail.google.com,2004:1383746934228011210 [作者] =&gt; SimpleXMLElement对象([name] =&gt; Webs [email] =&gt; EMAIL)))

我想要它,以便结果不显示“SimpleXMLElement对象”等,只显示实际有用的信息(主题,电子邮件内容,日期等)

我尝试过使用str_replace,但它不起作用。

2 个答案:

答案 0 :(得分:1)

尝试类似:

echo "Title: ".$xml->title.", tagline: ".$xml->tagline;

您可能需要在上面添加一些额外的路径,具体取决于XML的格式。

您也可以尝试

print_r((array)$xml);

如:

<?php
$xml = "<x><title>Blah</title><fred>bob</fred></x>";
$s =  simplexml_load_string($xml);
print_r((array)$s);

输出:

Array
(
    [title] => Blah
    [fred] => bob
)

答案 1 :(得分:0)

使用print_r()只会为您提供人类可读的输出。您可以将其转换为XML或JSON,以便更符合您的要求。

尝试转换为json。

$json = json_encode($xml);
echo $json;