Как правильно разобрать этот текст с помощью PHP? Я на полпути
У меня есть этот блок текста (из Discogs API) с подробной информацией о группах, которые содержат слово "Pink"...
Я пытаюсь понять, как правильно извлечь имена исполнителей из этого блока текста. Моя попытка была:
<?php
$url = "https://api.discogs.com/database/search?type=artist&q=pink"; // add the resource info to the url. Ex. releases/1
//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);
function textParser($text, $css_block_name){
$end_pattern = '], "';
switch($css_block_name){
# Add your pattern here to grab any specific block of text
case 'title';
$end_pattern = '", "';
break;
}
# Name of the block to find
$needle = "\"{$css_block_name}\":";
# Find start position to grab text
$start_position = stripos($text, $needle) + strlen($needle);
$text_portion = substr($text, $start_position, stripos($text, $end_pattern, $start_position) - $start_position + 1);
$text_portion = str_ireplace("[", "", $text_portion);
$text_portion = str_ireplace("]", "", $text_portion);
return $text_portion;
}
$blockTitle = textParser($output, 'title');
echo $blockTitle. '<br/>';
?>
но это дает эту ошибку:
Предупреждение: stripos(): смещение не содержится в строке в C:\xampp\htdocs\WellItsFixed3\TTpage1.php в строке 41
Строка 41
$text_portion = substr($text, $start_position, stripos($text, $end_pattern, $start_position) - $start_position + 1);
Конечная цель состоит в том, чтобы иметь возможность представлять извлеченные названия групп в списке.
Любое понимание приветствуется. Спасибо.
1 ответ
Решение
Это явно строка в кодировке JSON, и вы перебиваете свой подход. Просто делать:
$data = json_decode($your_string);
а также $data
будет содержать всю информацию в структурированном виде, подробности см. в руководстве json_decode().