[英]Extract certain values from XML response to create custom JSON array
Hi Sorry if this is a silly question but I would appreciate any help getting pointed in the right direction.嗨,对不起,如果这是一个愚蠢的问题,但我会很感激任何帮助指出正确的方向。 I have two API's I am using, the first one returns XML with what i need plus more.
我有两个正在使用的 API,第一个返回 XML 以及我需要的内容和更多内容。 The second API takes a JSON object.
第二个 API 采用 JSON 对象。 What i am stuck on is getting the values i need out of the XML response and making the JSON object.
我所坚持的是从 XML 响应中获取我需要的值并制作 JSON 对象。 At the moment i have this XML:
目前我有这个 XML:
<?xml version="1.0" encoding="UTF-8"?>
<wapi>
<reply status="0" error_str="" error_code="0">
<item>
<firstname>Jim</firstname>
<lastname>Doe</lastname>
<accountnum>10037529</accountnum>
<contact_number>353123451234</contact_number>
</item>
<item>
<firstname>Jack</firstname>
<lastname>Doe</lastname>
<accountnum>10037530</accountnum>
<contact_number>353123452345</contact_number>
</item>
</reply>
</wapi>
And I would like to get all instaces of the "accountnum" value and inserting it into a JSON object like the below with a static key called "customer-id", this JSON will then be sent to the second API.我想获取“accountnum”值的所有实例,并将其插入到如下所示的 JSON 对象中,并使用名为“customer-id”的静态键,然后将此 JSON 发送到第二个 API。
[
{
"customer-id": "10037529"
},
{
"customer-id": "10037530"
}
]
I am using PHP to do this and i have tried json_encode to change to JSON and then parse it but I couldn't get that to work i also turned it into an array and looped over it but couldn't get the value out.我正在使用 PHP 来执行此操作,并且我尝试将 json_encode 更改为 JSON,然后对其进行解析,但我无法使其正常工作,我也将其转换为一个数组并对其进行循环,但无法获取该值。 I am only writing here as i have searched for hours and cant seem to find anything close to what i am doing, or maybe im just going about this wrong.
我只是在这里写作,因为我已经搜索了几个小时,似乎找不到与我正在做的事情相近的东西,或者我可能只是在做这个错误的事情。
Again any pointers would be great, thanks.再次任何指针都会很棒,谢谢。
Consider you have your xml in $str
variable.考虑你在
$str
变量中有你的 xml。
$xml = simplexml_load_string ($str);
$data = [];
foreach ($xml->reply->item as $item) {
$data[] = ['customer-id' => (string)$item->accountnum];
}
echo json_encode($data);
Output:
[{"customer-id":"10037529"},{"customer-id":"10037530"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.