
Originally Posted by
kduv
json_encode/decode are great functions to transform XML into associative arrays.
Don't do this, it a waste of time and effort. You were very close originally, see the comments within your code below.
PHP Code:
// 1. No need to urlencode() the whole URL, in fact this breaks everything.
$apiurl = urlencode("http://api.preachingcentral.com/bible.php?passage=$passage&version=$version");
// 2. No need to file_get_contents() as SimpleXML can read URLs.
// In fact the 'true' says you are passing in a URL.
$data = file_get_contents('$apiurl');
$bible = new SimpleXMLElement($data,0,true);
$dtext=array();
// 3. Here $bible is the <bible> XML element.
// Looping over $bible will loop over only its immediate children.
// These are the <title>, <range>, <cache> and <time> elements.
// You want to loop over the <item> elements which are held
// within the <range> element, within the <bible> element.
foreach ($bible as $item)
{
$dtext[]=$item->text;
}
Here is a similar script doing what you want, that works; and without the crazy JSON encode/decode.
PHP Code:
// Properly build the URL, only encoding the query string.
$parameters = array("passage" => $passage, "version" => $version);
$apiurl = "http://api.preachingcentral.com/bible.php?" . http_build_query($parameters);
// Fetch the XML from $apiurl.
$bible = new SimpleXMLElement($apiurl, null, TRUE);
$dtext = array();
foreach ($bible->range->item as $item) {
$dtext[] = (string) $item->text;
}
See this example running online.
Bookmarks