In the absence of a unified standard When a system connects to multiple external systems, it often encounters heterogeneous response data from the request interface. It may return XML or JSON. In addition to the different return types, the content structure is also different. Taking the XML type as an example, Interface 1 returns content
It is obviously unreasonable to process each format of content in our system. In the above content, we only care about three types of information, namely business ID, status value and description information. Can we abstract these three types of information? After obtaining this information, we can perform business logic processing.
Parsing XML and JSON
According to business abstraction, we need to obtain three types of information from XML or JSON content. We will use XPath and JSONPath to parse here. . For example, to obtain important information about interface 1, we can set three XPath expressions,
bid, code and descriptionCorresponds to the field name defined by our system. The same goes for parsing JSON content, except that the JSONPath expression is defined.
Process data content in two steps
Suppose we obtain bid,code and from the original XML and JSON data descriptionInformation, obtained from interface 1
Assume we get the status value from the interface 1 document 200 indicates that the request was successful , we learned from the interface 2 document that the status value 1 indicates that the request was successful. Although they all indicate that the request was successful, we still cannot save them intact into our business-related tables (of course these response data It still needs to be saved in another record table, at least to facilitate troubleshooting). Assume that our business-related tables are designed like this
##Field name
Type
Description
bid
string
Business ID
code
int
Status value, 0=initial, 1=requesting, 2=success, 3=failure
The above is the detailed content of Example code sharing of some techniques for parsing XML and JSON content. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn