Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data from .USX file using php

Tags:

php

xml

I have one .usx file and i want to fetch data from it accordingly. But now finding any way to do it. Please help me out. usx file link

I had tried the below code

$xml=simplexml_load_file("uploads/American-Standard-Version-Bible-master/usx/01-GEN.usx") or die("Error: Cannot create object");

foreach($xml->children() as $book)
{
    // echo "<pre>";
    // print_r($book);

     echo "Book Name:".$book->attributes()->code."<br/>";
    if($book->attributes()->number != "" )
    {
         echo "chapter : ".$book->attributes()->number."<br />";
    }
    foreach ($book->verse as $value) {
      // echo "<pre>";
      // print_r($value);
       echo "Verses Number : ".$value->attributes()->number."<br />";
    }

    echo "book : ".$book."<br />";
    echo "<hr/>";


}

}

OUTPUT : this is the output

I want output one by one of all verse rather then all at once

like image 474
Atmiya Kolsawala Avatar asked Sep 15 '18 05:09

Atmiya Kolsawala


1 Answers

The problem can be that SimpleXML just doesn't give you enough control over XML that has more than a simple structure. So trying to get the text inbetween the <verse> tags is difficult. If instead you use DOMDocument, this has much more detail and control over your document.

The code below just reads through the document and mostly checks the node names to work out what it should be displaying - so for the <chapter> element, it will output the number attribute. The only difference is that when looking through the main <para> elements which contain the <verse> and text mixed together, it looks for a node type of XML_TEXT_NODE, which as you might expect is the verse text, so it just outputs the contents at that point.

$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load("01-GEN.usx");

foreach ( $dom->documentElement->childNodes as $element )    {
    if ( $element->nodeName == "book" )    {
        echo "Book Name:".$element->getAttribute("code")."<br/>";
    }
    else if ( $element->nodeName == "chapter" )    {
        echo "chapter:".$element->getAttribute("number")."<br/>";
    }
    else if ( $element->nodeName == "para" )    {
        foreach ( $element->childNodes as $verse )    {
            if ( $verse->nodeName == "verse" )    {
                echo "verse:".$verse->getAttribute("number")."<br/>";
            }
            else if ( $verse->nodeType == XML_TEXT_NODE )   {
                echo $verse->nodeValue."<br/>";
            }
        }
    }
}
like image 82
Nigel Ren Avatar answered Oct 03 '22 16:10

Nigel Ren