gpt4 book ai didi

php - simplexml_load_string 不解析我的 XML 字符串。字符集问题?

转载 作者:行者123 更新时间:2023-12-05 03:15:20 27 4
gpt4 key购买 nike

我正在使用以下 PHP 代码从 NOAA 的潮汐报告站 API 读取 XML 数据:

$rawxml = file_get_contents(
"http://opendap.co-ops.nos.noaa.gov/axis/webservices/activestations/"
."response.jsp?v=2&format=xml&Submit=Submit"
);
$rawxml = utf8_encode($rawxml);
$ob = simplexml_load_string($rawxml);
var_dump($ob);

不幸的是,我最终显示了这个:

object(SimpleXMLElement)#246 (0) { }

在我看来,XML 格式完全正确 - 为什么不能解析?通过查看另一个问题 ( Simplexml_load_string() fail to parse error ),我认为 header 可能是问题所在 - http 调用确实返回了“ISO-8859-1”的字符集值。但是添加 utf8_encode() 调用似乎并不能解决问题。

特别令人困惑的是 simplexml_load_string() 实际上并没有失败——它返回了一个愉快的 XML 数组,只是里面什么都没有!

最佳答案

您被 SimpleXML 书中最古老的技巧愚弄了(也让我被愚弄了):SimpleXML 不将整个文档解析为 PHP 对象,它为内部结构提供 PHP API。像 var_dump 这样的函数看不到这个结构,所以不要总是对对象中的内容给出有用的想法。

它看起来“空”的原因是它列出了默认命名空间中根元素的子元素——但实际上没有,它们都在“soapenv:”命名空间中。

要访问命名空间元素,您需要使用 the children() method ,传入完整的命名空间名称(推荐)或其本地前缀(更简单,但可能会因另一端生成文件的方式发生变化而中断)。要切换回“默认命名空间”,请使用 ->children(null)

因此您可以获得第一个 stationV2 元素的 ID 属性,如下所示 (live demo):

// Define constant for the namespace names, rather than relying on the prefix the remote service uses remaining stable
define('NS_SOAP', 'http://schemas.xmlsoap.org/soap/envelope/');

// Download the XML
$rawxml = file_get_contents("http://opendap.co-ops.nos.noaa.gov/axis/webservices/activestations/response.jsp?v=2&format=xml&Submit=Submit");
// Parse it
$ob = simplexml_load_string($rawxml);

// Use it!
echo $ob->children(NS_SOAP)->Body->children(null)->ActiveStationsV2->stationsV2->stationV2[0]['ID'];

我写了some debugging functions to use with SimpleXML这应该比 var_dump 等误导性小得多。Here's a live demo with your code and simplexml_dump .

关于php - simplexml_load_string 不解析我的 XML 字符串。字符集问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18667478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com