加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 使用wp_remote_get在WordPress中使用XML

发布时间:2020-12-13 17:23:32 所属栏目:PHP教程 来源:网络整理
导读:我怀疑我遗漏了一些非常基本和明显的东西,所以请提前道歉! 我一直在使用simple_xml_load来处理XML文件,但是我的客户端托管提供程序阻止通过此方法加载外部文件.我现在正在尝试使用WordPress中内置的wp_remote_get函数重建我的工作. 这是我的代码(注意:在此
我怀疑我遗漏了一些非常基本和明显的东西,所以请提前道歉!

我一直在使用simple_xml_load来处理XML文件,但是我的客户端托管提供程序阻止通过此方法加载外部文件.我现在正在尝试使用WordPress中内置的wp_remote_get函数重建我的工作.

这是我的代码(注意:在此示例中,密钥和shelter ID是通用的):

$url = "http://api.petfinder.com/shelter.getPets?key=1234&count=20&id=abcd&status=A&output=full";
$pf_xml = wp_remote_get( $url );
$xml = wp_remote_retrieve_body($pf_xml);

使用它,我可以检索我需要的所有数据的数组,但我无法弄清楚如何定位特定数据.这是print_r($xml)的输出:

<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd">
    <header>
        <version>0.1</version>
        <timestamp>2013-03-09T15:03:46Z</timestamp>
        <status>
        <code>100</code>
        <message/>
        </status>
    </header>
    <lastOffset>5</lastOffset>
    <pets>
        <pet>
            <id>13019537</id>
            <name>Jordy</name>
            <animal>Dog</animal>
        </pet>
        <pet>
            <id>13019888</id>
            <name>Tom</name>
            <animal>Dog</animal>
        </pet>
    </pets>
</petfinder>

例如,如果我想回显状态代码,我该怎么做?使用simplexml,我会写$xml-> header-> status->代码.我似乎无法弄清楚代码结构是什么,使用wp_remote_get与数组做类似的事情.

提前致谢!

解决方法

到目前为止,您的代码确实将XML检索为字符串:

$url      = "http://api.petfinder.com/shelter.getPets?key=1234&count=20&id=abcd&status=A&output=full";
$response = wp_remote_get($url);
$body     = wp_remote_retrieve_body($response);

要像在simplexml_load_file之前那样将字符串(而不是URL)加载到SimpleXMLElement中(您没有显示具体代码,所以我假设您是根据您的描述以这种方式执行的),您现在需要使用simplexml_load_string加载字符串代替:

$xml  = simplexml_load_string($body);
$code = $xml->header->status->code;

我稍微改变了你的变量名(特别是使用wp_remote_ *函数),以便更清楚地了解这些变量的含义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读