【发布时间】:2015-05-11 04:06:20
【问题描述】:
我正在尝试解析来自 Ontraport API 的响应,该响应以丑陋的 XML 格式返回。
<result>
<contact id="1" date="1424746532" dlm="1425357692" score="0.00" purl="" bulk_mail="1">
<Group_Tag name="Contact Information">
<field name="Company">Test.com</field>
<field name="Email">test@test.com</field>
<field name="Group"/>
<field name="Specialty"/>
<field name="User ID"/>
<field name="Display First"/>
<field name="Display Last"/>
</Group_Tag>
</contact>
</result>
我正在使用SimpleXML 和simplexml_load_string 函数。当我 var_dump 来自该函数的响应时,我得到以下输出:
object(SimpleXMLElement)#1 (1) {
["contact"]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(6) {
["id"]=>
string(1) "1"
["date"]=>
string(10) "1424746532"
["dlm"]=>
string(10) "1425357692"
["score"]=>
string(4) "0.00"
["purl"]=>
string(0) ""
["bulk_mail"]=>
string(1) "1"
}
["Group_Tag"]=>
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
array(1) {
["name"]=>
string(19) "Contact Information"
}
["field"]=>
array(7) {
[0]=>
string(8) "Test.com"
[1]=>
string(13) "test@test.com"
[2]=>
object(SimpleXMLElement)#4 (1) {
["@attributes"]=>
array(1) {
["name"]=>
string(5) "Group"
}
}
[3]=>
object(SimpleXMLElement)#5 (1) {
["@attributes"]=>
array(1) {
["name"]=>
string(9) "Specialty"
}
}
[4]=>
object(SimpleXMLElement)#6 (1) {
["@attributes"]=>
array(1) {
["name"]=>
string(7) "User ID"
}
}
[5]=>
object(SimpleXMLElement)#7 (1) {
["@attributes"]=>
array(1) {
["name"]=>
string(13) "Display First"
}
}
[6]=>
object(SimpleXMLElement)#8 (1) {
["@attributes"]=>
array(1) {
["name"]=>
string(12) "Display Last"
}
}
}
}
}
}
我如何检索公司和电子邮件值,或从那里检索任何特定字段,我不知道它们是空的还是有值。
我看不到那些有值的字段名称,我不能假设字段顺序。
编辑:我不认为这是 @Rizier123 所说的重复,因为我正在尝试基于元素属性检索项目,而我什至没有进入var_dump 具有值的字段的属性。因此,针对该其他问题的建议和接受的解决方案不适用于此处。 正如他所问的,我正在添加我用来测试这个的完整和真实的代码:
$response = '<result>
<contact id="1" date="1424746532" dlm="1425357692" score="0.00" purl="" bulk_mail="1">
<Group_Tag name="Contact Information">
<field name="Company">Test.com</field>
<field name="Email">test@test.com</field>
<field name="Group"/>
<field name="Specialty"/>
<field name="User ID"/>
<field name="Display First"/>
<field name="Display Last"/>
</Group_Tag>
</contact>
</result>';
$responseData = simplexml_load_string($response);
var_dump($responseData);
【问题讨论】:
-
@Rizier123 我不认为这是重复的,因为我正在尝试基于元素属性检索项目,而我什至没有进入 var_dump 字段的属性有一个价值。因此,针对其他问题提出和接受的解决方案不适用于此处。
-
那么请同时附上如何获取 xml 以及如何打印的代码! (您的完整和真实代码)
-
@Rizier123 完成。我不认为它增加了任何有趣的东西,但我添加了它。它是我的 完整 和 真实 代码,因为我首先要做一个最简单的测试。
-
您是否尝试循环通过“字段”数组并使用 $field[n]->attributes() 获取属性?它会返回任何东西吗?