php – 使用wp_remote_get在WordPress中使用XML

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 使用wp_remote_get在WordPress中使用XML脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我怀疑我遗漏了一些非常基本和明显的东西,所以请提前道歉!

我一直在使用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_ *函数),以便更清楚地了解这些变量的含义.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 使用wp_remote_get在WordPress中使用XML全部内容,希望文章能够帮你解决php – 使用wp_remote_get在WordPress中使用XML所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。