I am trying to parse XML in PHP and then put it as an object in JavaScript to Materialize CSS autocomplete.
I tried to parse it in PHP and put it as an object in JavaScript with json_encode($array)
But it didn't work. Autocomplete shows just numbers.
You have to put data as an object in "data". And it must be as "string": 'http://url'
the URL is for a thumbnail. But I want it as "string": null
. So there won't be a thumbnail.
This is a sample from Materialize CSS documentation: https://materializecss.com/autocomplete.html
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});
My XML file:
<tittle>
<topic>
<name>PHP</name>
</topic>
<topic>
<name>JS</name>
</topic>
<topic>
<name>CSS</name>
</topic>
</tittle>
My code:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons'>
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete" class="autocomplete">
<label for="autocomplete">Autocomplete</label>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?php
$xml = simplexml_load_file("xml.xml");
$array = array();
foreach($xml->topic as $topic)
{
$array[] = $topic->name;
}
?>
<script >
var array = <?php echo json_encode($array); ?>;
console.log(array);
$(function () {
$('input.autocomplete').autocomplete({
data: array
});
});
</script>
</body>
</html>
An output of console.log(array);
:
The autocomplete is displaying just numbers (0-2). I think those numbers are array indexes.
I think I must change the array structure to "string_from_array": null
Is there any way how to do it? Thank you for response