【问题标题】:XML Parsing with Symfony使用 Symfony 进行 XML 解析
【发布时间】:2016-07-11 05:48:49
【问题描述】:

我在 url 中有一个 XML 文件。我想从 xml 中解析数据并为我的实体补充水分。

我已经编写了代码(爬虫),但这不起作用(空响应)。

public function getUsersAction(Request $request)
{
    $crawler = new Crawler();
    $crawler->addXmlContent(
        file_get_contents(
            'http://localhost/myproject/web/feed-users.xml'
        )
    );

    json_encode($crawler);

    return new JsonResponse(
        array(
            'crawler' => $crawler
        )
    );
}

谢谢

【问题讨论】:

    标签: php xml symfony


    【解决方案1】:

    试试看。

     public function ConvertXmlToJson(){
        $url = 'https://host/yourxml.xml';
        $fileContents = file_get_contents($url);
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $simpleXml = simplexml_load_string($fileContents);
    
        return new JsonResponse($simpleXml);
    }
    

    【讨论】:

      【解决方案2】:

      您需要在注入 xml 提要后解析您的 $crawler。

      use Symfony\Component\CssSelector\CssSelector;
      
      public function getUsersAction(Request $request)
      {
      
          CssSelector::disableHtmlExtension();
          $crawler = new Crawler(file_get_contents('http://localhost/myproject/web/feed-users.xml'));
      
          $value = $crawler->filter('.someCssSelectorForInstance');
      }
      

      您可以在注入 xml 提要后dump($crawler),您会看到您的爬虫已准备就绪

      【讨论】:

        猜你喜欢
        • 2013-07-18
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多