首页 > 解决方案 > 从 XML 实现 CSS 自动完成

问题描述

我正在尝试在 PHP 中解析 XML,然后将其作为 JavaScript 中的对象来实现 CSS 自动完成。

我试图用 PHP 解析它并将它作为一个对象放在 JavaScript 中,json_encode($array)但它没有用。自动完成只显示数字。

您必须将数据作为对象放入“数据”中。它必须是"string": 'http://url'缩略图的 URL。但我希望它为"string": null. 所以不会有缩略图。

这是 Materialize CSS 文档中的一个示例:https ://materializecss.com/autocomplete.html

  $(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },
    });
  });

我的 XML 文件:

<tittle>

<topic>
<name>PHP</name>
</topic>

<topic>
<name>JS</name>
</topic>

<topic>
<name>CSS</name>
</topic>

</tittle>

我的代码:

<!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>

的输出console.log(array);

自动完成仅显示数字 (0-2)。我认为这些数字是数组索引。

我想我必须将数组结构更改为"string_from_array": null

有什么办法吗?感谢您的回复

标签: javascriptphpcssxml

解决方案


尝试:

foreach($xml->topic as $topic)
   {
   $array[$topic->name] = null;  
   }

推荐阅读