php - Convert SimpleXMLElement to JSON array -
I have a stored procedure (SQL Server) that gives the XML given below which can be found at the top of the given search terms 20 is the ranking month With the following PHP, I can get this XML and Loop through:
foreach ($ objSearchTerms-> search terms as words) {echo $ terms-> ; SearchTerm; };
Fatching works and gives correct data However, my problem is that I need to create an array outside of it which looks like below to use in JS.
Can anyone tell me how can I get it? The text portion of the array will be my search term ( $ terms-> searchTerm
) and weight will only count down to 20 to 0.
My simple XML:
& lt; Rank & gt; & Lt; SearchTerms & gt; & Lt; Rank & gt; 1 & lt; / Ranks & gt; & Lt; Search & gt; Item 1 & lt; / SearchTerm & gt; & Lt; Quantity & gt; 11 & lt; / Quantity & gt; & Lt; / SearchTerms & gt; & Lt; SearchTerms & gt; & Lt; Rank & gt; 2 & lt; / Ranks & gt; & Lt; Search & gt; Item 2 & lt; / SearchTerm & gt; & Lt; Quantity & gt; 8 & lt; / Quantity & gt; & Lt; / SearchTerms & gt; & Lt; SearchTerms & gt; & Lt; Rank & gt; 3 & lt; / Ranks & gt; & Lt; Search & gt; Item 3 & lt; / SearchTerm & gt; & Lt; Quantity & gt; 5 & lt; / Quantity & gt; & Lt; / SearchTerms & gt; // ... & lt; / Ranks & gt;
Expected Result:
var word_array = [{text: "item 1", weight: 20}, {text} : "Item 2", weight: 1 9}, {text: "item 3", weight: 18}, // ...];
I tried to do something like the following, but it does not work and probably is not the right approach:
$ Count = 21; Foreign exchange ($ objSearchTerms-> search terms as $ terms) {$ count--; Echo "{text: '" $ word-> SearchTerms ", Weight:". $ Counts "},"; }
this code can help you
$ Xml = simplexml_load_file ("file.xml"); $ Result = []; $ Counts = 20; Forex Currency ($ xml-> Keywords as $ Value) {$ child = []; $ Child ['text'] = (string) $ value- & gt; SearchTerms; $ Baby ['weight'] = $ count--; $ Result [] = $ child; } $ Json_string = json_encode ($ result);
I get the result
[{"text": "item 1", "weight": 20}, {"text": " Item 2 "," weight ": 1 9}, {" text ":" item 3 "," weight ": 18}]
Comments
Post a Comment