简体   繁体   中英

Using xpath to query XML in PHP

I am using xpath for the first time to query an xml document for a value and return the corresponding name value. I have been reading numerous different sources on the topic but I can't seem to get it to output correctly. Here is my XML :

<?xml version="1.0" encoding="utf-8"?>
<books>
  <book>
    <name>Genesis</name>
    <abrv>GEN</abrv>
    <title>The First Book of Moses</title>
  </book>
  <book>
    <name>Exodus</name>
    <abrv>EXO</abrv>
    <title>The Second Book of Moses</title>
  </book>
  <book>
    <name>Leviticus</name>
    <abrv>LEV</abrv>
    <title>The Third Book of Moses</title>
  </book>
</books>

Here is my PHP / HTML :

<?php $root = $_SERVER['DOCUMENT_ROOT'] . "/";
$bookID = 'GEN';
$xml = simplexml_load_file( $root . 'assets/xml/books.xml' ) or die( "No Page Data Found" );
$bookName = $xml->xpath( '//book[abrv="'.$bookID.'"]/name' );
?>
<article id="verseOfDay">
  <div class="container">
    <h2>verse of the day</h2>
    <h6><?php echo $bookName; ?></h6> // Line 19
    <p></p>
  </div>
</article>

Finally, here is the notice that I am receiving:

NOTICE: ARRAY TO STRING CONVERSION IN /HOME/#####/MYWEBSITE.COM/ASSETS/INCLUDES/VERSEOFTHEDAY.PHP ON LINE 19 ARRAY

What am I doing wrong? In this example I am expecting it to output Genesis in the tag.

The SimpleXML xpath function returns an array of results, which will be empty if no result is found. So you need to check for that, and if you get a result, it will be at $bookName[0] . Something like this will work:

$bookNames = $xml->xpath( '//book[abrv="'.$bookID.'"]/name' );
$bookName = empty($bookNames) ? 'Not Found' : $bookNames[0];
?>
<article id="verseOfDay">
  <div class="container">
    <h2>verse of the day</h2>
    <h6><?php echo $bookName; ?></h6>
    <p></p>
  </div>
</article>

Demo on 3v4l.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM