I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML… but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp
is the response from eBay. It’s their full length XML that is successfully parsed with the code below.
For example… $valueName
could be Grade
. And then I go into the next foreach loop and get the values for this. These values
may be 10, 9.5, 9
etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this…
NAME
—– Value
—– Value
—– Value
NAME
—– Value
NAME
etc etc
For a JSON response… Im looking for something like…
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay’s response is like this (there are A LOT more <aspect>
and <valueHistogram>
)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
3
Answers
To encode it (and assuming SimpleXML), then it’s just a case of building each internal
$aspect
data array and then adding the values to it. I use(string)
to ensure the data is not stored as a SimpleXMLElement, which can cause side effects…with the sample XML, this gives…
Create one single array
$resultArray
and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,