chathurachaminda
chathurachaminda

Reputation: 41

Read XML file in laravel

I'm trying to read xml file in laravel i

My XML file is in storage folder inside JSON folder file name ashan.xml I create new route

Route::resource('test', 'Backend\TestController');

When I hit the route this Controller get call

class TestController extends Controller{
public function index()
{
 $xml = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', file_get_contents(storage_path() . "/json/ashan.xml"));

$xmlObject = simplexml_load_string($xml);
var_dump((string)$xmlObject->return->verificationResult->individualResult->method);
}}

this is my xml

I want to get value inside <overallVerificationStatus> tag.

Upvotes: 1

Views: 12016

Answers (2)

Kumar Praveen
Kumar Praveen

Reputation: 134

Try the below code it may help you.

public function index(){
    $xmlString = file_get_contents(storage_path() . "/json/ashan.xml"));
    $xmlObject = simplexml_load_string($xmlString);
            
    $json = json_encode($xmlObject);
    $array = json_decode($json, true);    
}

Upvotes: 5

Mathal
Mathal

Reputation: 55

I recommend using XMLReader, something like this:

    $counter = 0;
    $variable = [];
    $variable[$counter] = new \stdClass();
    $xmlFile = "/file/path.xml";
    $xml = new \XMLReader();
    $xml->open($xmlFile);
    try {
        while ($xml->read()) {
            if ($xml->nodeType == \XMLReader::ELEMENT) {
                //assuming the values you're looking for are for each "item" element as an example
                if ($xml->name == 'item') {
                    $variable[++$counter] = new \stdClass();
                    $variable[$counter]->thevalueyouwanttoget = '';
                }
                if ($xml->name == 'thevalueyouwanttoget') {
                    $variable[$counter]->thevalueyouwanttoget = $xml->readString();
                }
            }
        }
    } catch (Exception $e) {
        ....
    } finally() {
    $xml->close();
    }

Upvotes: 0

Related Questions