Answer the question
In order to leave comments, you need to log in
How to work with Sphinx in PHP?
Hello. I had a problem searching the site and decided to try Sphinx, installed, configured, but I can not find a code example for PHP. I found only the sphinxapi.php library itself. Are there any examples of how to use sphinx in php anywhere?
ps I know how to use Google, I made such a code, but I don’t know how to get the data:
<?php
include_once('sphinxapi.php');
// Создадим объект - клиент сфинкса и подключимся к нашей службе
$s = new SphinxClient;
$s->setServer("localhost", 9312);
$s->setMatchMode(SPH_MATCH_ANY);
$s->setMaxQueryTime(3);
$result = $s->query("кошка");
SELECT `id`,`from_id`,`from_name`,`title`,`description`, `category` FROM `konkurs` WHERE `published` = 1
Answer the question
In order to leave comments, you need to log in
import csv
import xml.etree.ElementTree as ET
xml_data = """<?xml version="1.0"?>
<Root>
...
</Root>"""
root = ET.fromstring(xml_data)
header = set()
rows = []
for subroot in root:
row = {}
for level in subroot:
header.add(level.tag)
row[level.tag] = level.text
rows.append(row)
with open('out.csv', 'w') as file:
writer = csv.DictWriter(file, fieldnames=sorted(header))
writer.writeheader()
writer.writerows(rows)
>>> import xml.etree.ElementTree as etree
>>> import csv
>>> import sys
>>>
>>> text = """\
... <Root>
... <SubRoot>
... <Level1>A</Level1>
... <Level2>B</Level2>
... <Level3>C</Level3>
... <Level4>D</Level4>
... </SubRoot>
...
... <SubRoot>
... <Level1>1</Level1>
... <Level2>2</Level2>
... <Level3>3</Level3>
... </SubRoot>
... </Root>
... """
>>>
>>> root = etree.fromstring(text)
>>>
>>> out = [[i.text for i in node] for node in root]
>>> out
[['A', 'B', 'C', 'D'], ['1', '2', '3']]
>>>
>>> out = [(i + [None] * (4 - len(i))) for i in out]
>>> out
[['A', 'B', 'C', 'D'], ['1', '2', '3', None]]
>>>
>>> writer = csv.writer(sys.stdout)
>>> writer.writerows(out)
A,B,C,D
1,2,3,
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question