Converting XML information into a JSON array on the Index.php page

I apologize if this question seems foolish, but I am struggling to figure things out. My goal is to extract specific values from an XML file and convert them into a JSON array within my PHP script.

Here is how I am currently fetching data from the XML file and displaying the JSON output based on different cases:

switch ($creditId) {
case 123:
    $xml = new XMLReader;
    $xml->open('123.xml');

    $doc = new DOMDocument;

    while ($xml->read() && $xml->name !== 'Decision');

    while ($xml->name === 'Decision')
    {

        $node = simplexml_import_dom($doc->importNode($xml->expand(), 
true));

        $reason_text = $node->Reason->ReasonText ;
        echo "$reason_text \n";

        // move to the next <Decision>
        $xml->next('Decision');
    }

    echo '[{
            "creditId": 123,
            "client": "Peter",
            "Decision": "Solo" ,
            "Factors": ["REASONTEXT1","REASONTEXT2"]
    }]';

    break;
case 789:

    $xml = new XMLReader;
    $xml->open('789.xml');

    $doc = new DOMDocument;

    while ($xml->read() && $xml->name !== 'Decision');

    while ($xml->name === 'Decision')
    {

        $node = simplexml_import_dom($doc->importNode($xml->expand(), 
true));

        $reason_text = $node->Reason->ReasonText ;
        echo "$reason_text \n";

        // move to the next <Decision>
        $xml->next('Decision');
    }

    echo '[{
            "creditId": 789,
            "client": "Jonas",
            "Decision": "Random",
            "Factors": ["REASONTEXT1","REASONTEXT2"]
    }]';
    break;
default:
    http_response_code(404);
}

The placeholders REASONTEXT1 AND REASONTEXT2 are where the $reason_text variable values should be displayed in the JSON array. For example, the current JSON output for case 123 displays RandomReason1 and RandomReason2 as follows:

 RandomReason1 
 RandomReason2
    [{
            "creditId": 123,
            "client": "Peter",
            "Decision": "Solo",
            "Factors": ["REASONTEXT1","REASONTEXT2"]
    }]

My desired outcome is to have the values displayed like this:

    [{
            "creditId": 123,
            "client": "Peter",
            "Decision": "Solo",
            "Factors": ["RandomReason1","RandomReason2"]
    }]

In conclusion, I am looking to transform specific XML data into a JSON array. Thank you for your assistance!

Answer №1

It's important to note that this is specifically a PHP question, not related to Vue or JavaScript. Take a look at your code. The issue is that the RandomReason1 and RandomReason2 are being printed before the JSON because of the echo "$reason_text \n"; statement in your code. Instead, you should store the values inside an array and only echo it when necessary. For example:

$reasons[] = $reason_text;
...
echo '[{
    "creditId": 789,
    "client": "Jonas",
    "Decision": "Random",
    "Factors": '.json_encode($ereasons).'
}]';

Answer №2

It can be quite challenging without having access to your XML file, but let's give it a shot :-)

Assuming your XML structure resembles the following:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <Decision>
    <Reason>
      <ReasonText>This is my text #1</ReasonText>
    </Reason>
  </Decision>
  <Decision>
    <Reason>
      <ReasonText>This is my text #2</ReasonText>
    </Reason>
  </Decision>
</root>

I've prepared a sample implementation for case 123:

        case 123:
            $xml = new XMLReader;
            $xml->open('123.xml');

            $doc = new DOMDocument;

            while ($xml->read()){
                $nodename=$xml->localName;
                $depth=$xml->depth;
                $gipchecked=0;
                if ($nodename=='Decision' &&  $xml->nodeType == XMLReader::ELEMENT){ //EN van het type start elemenet
                        $node = simplexml_import_dom($doc->importNode($xml->expand(),true));
                        $reason_text.= $node->Reason->ReasonText ;
                        echo "Reason text contains: $reason_text \r\n";
                }

                // go to next <DecisionResponse>
                // $xml->next('Decision');
            }
            $xml->close();

            echo '[{
                    "creditId": 123,
                    "client": "Peter",
                    "Decision": "Solo" ,
                    "Factors": '.json_encode($reason_text).'
            }]';

        break;

If you execute this code snippet, you should see the following output in your browser:

Reason text contains: This is my text #1 

Reason text contains: This is my text #1This is my text #2 

[{ "creditId": 123, "client": "Peter", "Decision": "Solo" , "Factors": "This is my text #1This is my text #2" }]

Make sure to properly close your XML file using:

 $xml->close();

In addition, consider optimizing your switch statements by making them dynamic based on the filename and client information. Avoid repeating the same XMLREADER logic for each case - apply the DRY (Don’t Repeat Yourself) principle to reduce redundancy in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Arabic characters are not rendering correctly

As a beginner in html programming, I am looking to include Arabic text in my html file. I have added the following line containing Arabic text: <h1 dir="rtl">نص تجريبي لاختبار</h1> However, when I view the output, I am seeing u ...

Having trouble troubleshooting this issue where the object data is displaying in the console, but encountering an error when trying to use the resetValue

Index.html I am facing an issue while reading data from an object and the seek bar is giving a null error. The images and songs are stored locally, and I am trying to access them. <div class="music-player"> <div class="song&qu ...

Launching a Vue page via an external URL using a parameter

Currently, I am utilizing Laravel along with Vue in my web application. The main path for the app is '/app/main' which loads a specific vue component named 'main.vue'. One of the features on this page involves sending an email to a cus ...

When I use the Put method in Express, I receive a 200 status code, but no changes

Hello everyone, I recently attempted to implement my update function and tested it using Postman. I wanted to update the firstName field, but despite receiving a "HTTP/1.1" 200 response in the console, nothing was actually updated. This is the response bo ...

The Firefox dropdown menu constantly reverts back to the default option because of JavaScript running in AngularJS

I am currently developing an AngularJS app and encountering issues with select dropdown menus specifically in Firefox. Whenever I click on a select menu and hover over the options, it automatically resets the selected option back to the default/first opti ...

Hiding an endpoint in production build with NestJS: What you need to know

In order to streamline development and testing, I am looking to incorporate an endpoint that is not necessary for production. In my experience with Java, there are built-in solutions (like profiles) for this, but I have not stumbled upon similar documentat ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

Refreshing $scope variables within a function

$scope.myVar = cheese; function please(){ $scope.myVar = "New Value"; } google.maps.event.addListener(marker, 'click', please); This scenario is perplexing to me. I have a variable called "cheese" in the HTML and I anticipated that clicking ...

How come emphasizing certain characters in a string doesn't display the <b> tag in React.js?

I am trying to make a specific part of a string bold in my React.js app, but I'm not getting the expected result. Below is the code I am using and the output it produces: data?.map((item) => (<li key={item.id}>{item.title.replace(new RegExp(v ...

What is the best way to transform a Jackson JsonNode into a collection of custom user objects?

What is the optimal way to extract a specific internal Json array and convert it into a Java list using Jackson library? Assuming we have the following Json structure: { "objects":"that", "I":"dont care about", "objectsiwant":[{object1, object2,... ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Link data with router-link in Vue.js

I've set up a data variable within my component. The value of this variable is supposed to change dynamically based on the select box input. I'm trying to use this data value inside a router-link, but for some reason, it's not functioning as ...

ReactJS: Retrieving JSON file from the local server instead of the project folder

Here is the directory structure of my project: https://i.sstatic.net/JJcLx.png In my index.js file, I have the following code for loading the website.json file: index.js componentDidMount() { $.ajax({ url: "../website.json", type: "GE ...

What are the best methods for adjusting the layout of my Vue document based on changes in window size?

I'm a beginner with Vue, and this is my first attempt at using it rather than traditional HTML or CSS with some JavaScript added in. I'm struggling with formatting it to be responsive and adjust to different screen sizes. My media queries don&apo ...

Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS: productApp.directive('notification', function($timeout) { return { restrict : 'E', replace : true, scope : { type: "@", message: "@ ...

Tips for preventing curved links in a radial tree diagram created with d3

I am currently utilizing this code to generate a radial tree diagram for my data. However, I am looking to make a modification to eliminate curved links. My preference is for linear connections instead of curved ones as the curved links can make the visual ...

Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array... const orders = [ { "_id":"5d14a31490fb1e0012a3d2d8-1", "orderId":"0JL5ORM0JT-1", "created":"2019-06-27T11:05:56.377Z", "createdDate":"2019-06-2 ...

The input value does not update in the controller when using AngularJS ng-model

Why is it that when I print out console.log($scope.inputvalue), the variable does not update with the values I enter in the input field? Did I misunderstand the purpose of ng-model? If so, how can I pass a value from the view to the controller? (functi ...

What is preventing these AngularJS applications from functioning simultaneously?

I have a fully functioning AngularJS app that I developed as a standalone "CreateUser" widget. Now, I am working on creating a second widget called "ViewUsers," which will display a table of current users (with the intention of connecting them or keeping t ...

Utilizing AJAX and Javascript to assign text file contents to a JavaScript variable

After attempting to extract a list of words from a txt file and store it in a JavaScript variable for future use, I've encountered an issue. The problem lies in my inability to transfer the variable outside of the onreadystatechange function. Could th ...