Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

Laravel 8 How to display data in blade from an XML string as column of a record

I need to connect to an external database. I can get successfully all data from a Model.

$posts = Post::all();

One column of that table contains information in XML format. If you query one record, the column xml_data has something like:

<?xml version="1.0" encoding="UTF-8"?>
<post>
   <record id=1>
      <column>
         <subcolumn>Value 1</subcolumn>
         <subcolumn2>Value 2</subcolumn2>
      </column>
   </record>
</post>

Then, what I have tried is to convert the XML string to JSON as follows:

**LivewirePostsController.php**
$posts = Post::all();
$posts->each(function ($post,$key){
   $xml = simplexml_load_string($posyt->xml_data, "SimpleXMLElement", LIBXML_NOCDATA);
   $json = json_encode($xml);
   $post->json_data = $json;
});

Then, in my blade view,

@foreach($posts as $post)
   {{ $post->json_data }}
@endforeach

And the JSON data has the following data format:

{"Post":{"@attributes":{"id":"2"},"column":{"subcolumn 1":"Value 1","subcolumn 2":"value 2"}}} 

I have tried to display those values in a blade view

@foreach($posts as $post)
   {{ $post->json_data->Post}}
@endforeach

but I get the following error:

Trying to get property 'Post' of non-object

If I try:

{{ json_decode($post->json_data)->Post }}

I get the following error:

htmlspecialchars() expects parameter 1 to be string, object given.

Again, If I try:

@foreach(json_decode($post->json_data, true) as $key=>$value)
    key: {{ $key }} - value: {{ $value }}
@endforeach

I get the following error:

htmlspecialchars() expects parameter 1 to be string, array given

I also have found that the programmer used the Spatie array to XML package, but in the documentation, there's nothing related to achieve the opposite thing: XML to array or collection.

How can I display the values Value 1, Value 2? or what approach should I follow?

question from:https://stackoverflow.com/questions/65889267/laravel-8-how-to-display-data-in-blade-from-an-xml-string-as-column-of-a-record

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...