2012-03-19 2 views
1

Интересно, может ли кто-нибудь мне помочь.Использование Xpath для фильтрации записей

Я использую следующий скрипт для загрузки изображений из XML-файла в веб-страницу.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<?php 

    //This variable specifies relative path to the folder, where the gallery with uploaded files is located. 
    //Do not forget about the slash in the end of the folder name. 
    $galleryPath = 'UploadedFiles/'; 

    $thumbnailsPath = $galleryPath . 'Thumbnails/'; 

    $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; 

    $descriptions = new DOMDocument('1.0'); 
    $descriptions->load($absGalleryPath . 'files.xml'); 
?> 
<head> 
    <title>Gallery</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <link href="Libraries/fancybox/jquery.fancybox-1.3.1.css" rel="stylesheet" type="text/css" /> 
    <link href="Styles/style.css" rel="stylesheet" type="text/css" /> 
    <!--[if IE]> 
    <link href="Styles/ie.css" rel="stylesheet" type="text/css" /> 
    <![endif]--> 
    <script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script> 
    <script src="Libraries/fancybox/jquery.fancybox-1.3.1.pack.js" type="text/javascript"></script> 
    <script type="text/javascript"> 

    $(function() { $('a.fancybox').fancybox(); }); 

    </script> 
    <style type="text/css"> 
<!-- 
.style1 { 
    font-size: 14px; 
    margin-right: 110px; 
} 
.style4 {font-size: 12px} 
--> 
    </style> 
</head> 
<body style="font-family: Calibri; color: #505050; font-size: 9px; border-bottom-width: thin; margin-top: 5px; margin-left: -475px; margin-right: 1px; margin-bottom: -10px;"> 
<div align="right" class="style1"> <a href = "imagefolders.php" /> View Uploaded Images In Folder Structure <a/> &larr; View All Uploaded Images </div> 
    <form id="gallery" class="page"> 
    <div id="container"> 
    <div id="center"> 
     <div class="aB"> 
     <div class="aB-B"> 
      <?php if ('Uploaded files' != $current['title']) :?> 
      <?php endif;?> 
      <div class="demo"> 
      <div class="inner"> 
       <div class="container"> 
       <div class="gallery"> 
        <ul class="gallery-image-list"> 
        <?php for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) : 
          $xmlFile = $descriptions->documentElement->childNodes->item($i); 
          $name = htmlentities($xmlFile->getAttribute('originalname'), ENT_COMPAT, 'UTF-8'); 
          $description = htmlentities($xmlFile->getAttribute('description'), ENT_COMPAT, 'UTF-8'); 
          $folder = htmlentities($xmlFile->getAttribute('folder'), ENT_COMPAT, 'UTF-8'); 
          $source = $galleryPath . rawurlencode($xmlFile->getAttribute('source')); 
          $thumbnail = $thumbnailsPath . rawurlencode($xmlFile->getAttribute('thumbnail')); 
        ?> 
        <li class="item"> 
         <a class="fancybox" target="_blank" rel="original" href="<?php echo $source; ?>"><img class="preview" 
         alt="<?php echo $name; ?>" src="<?php echo $thumbnail; ?>" /></a>      </li> 
         <li class="item"></li> 
         <p><span class="style4"><b>Image Description:</b> <?php echo htmlentities($xmlFile->getAttribute('description'));?> <br /> 
          <b>Image contained in folder:</b> <?php echo htmlentities($xmlFile->getAttribute('folder'));?> </span><br /> 
          <?php endfor; ?> 
          </li> 
        </p> 
        </ul> 
       </div> 
       </div> 
      </div> 
      </div> 
     </div> 
     </div> 
    </div> 
    </div> 
     <div class="aB-a">  </div> 
     </div> 
    </div> 
    </div> 
    </form> 
</body> 
</html> 

Измененный код с XPath - NB Not A Рабочий раствор

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<?php 

    //This variable specifies relative path to the folder, where the gallery with uploaded files is located. 
    //Do not forget about the slash in the end of the folder name. 
    $galleryPath = 'UploadedFiles/'; 

    $thumbnailsPath = $galleryPath . 'Thumbnails/'; 

    $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; 

    $descriptions = new DOMDocument('1.0'); 
    $descriptions->load($absGalleryPath . 'files.xml'); 

    $xpath = new DOMXPATH($descriptions); 
?> 
<head> 
    <title>Gallery</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <link href="Libraries/fancybox/jquery.fancybox-1.3.1.css" rel="stylesheet" type="text/css" /> 
    <link href="Styles/style.css" rel="stylesheet" type="text/css" /> 
    <!--[if IE]> 
    <link href="Styles/ie.css" rel="stylesheet" type="text/css" /> 
    <![endif]--> 
    <script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script> 
    <script src="Libraries/fancybox/jquery.fancybox-1.3.1.pack.js" type="text/javascript"></script> 
    <script type="text/javascript"> 

    $(function() { $('a.fancybox').fancybox(); }); 

    </script> 
    <style type="text/css"> 
<!-- 
.style1 { 
    font-size: 14px; 
    margin-right: 110px; 
} 
.style4 {font-size: 12px} 
--> 
    </style> 
</head> 
<body style="font-family: Calibri; color: #505050; font-size: 9px; border-bottom-width: thin; margin-top: 5px; margin-left: -475px; margin-right: 1px; margin-bottom: -10px;"> 
<div align="right" class="style1"> <a href = "imagefolders.php" /> View Uploaded Images In Folder Structure <a/> &larr; View All Uploaded Images </div> 
    <form id="gallery" class="page"> 
    <div id="container"> 
    <div id="center"> 
     <div class="aB"> 
     <div class="aB-B"> 
      <?php if ('Uploaded files' != $current['title']) :?> 
      <?php endif;?> 
      <div class="demo"> 
      <div class="inner"> 
       <div class="container"> 
       <div class="gallery"> 
       <ul class="gallery-image-list"> 
        <?php for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) : 
          $name = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@originalname"); 
          $description = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@description"); 
          $folder = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@folder"); 
          $source = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@source");   
          $thumbnail = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@thumbnail"); 
        ?> 
        <li class="item"> 
         <a class="fancybox" target="_blank" rel="original" href="<?php echo $source; ?>"><img class="preview" 
         alt="<?php echo $name; ?>" src="<?php echo $thumbnail; ?>" /></a>      </li> 
         <li class="item"></li> 
         <p><span class="style4"><b>Image Description:</b> <?php echo $description;?> <br /> 
          <b>Image contained in folder:</b> <?php echo $folder;?> </span><br /> 

          </li> 
         </p> 
      <?php endfor; ?> 
</ul> 
       </div> 
       </div> 
      </div> 
      </div> 
     </div> 
     </div> 
    </div> 
    </div> 
     <div class="aB-a">  </div> 
     </div> 
    </div> 
    </div> 
    </form> 
</body> 
</html> 

и это файл XML, который загружается на страницу:

<?xml version="1.0" encoding="utf-8" ?> 
- <files> 
    <file name="Test 1/_47061196_greatbritainjpg.jpg" source="_47061196_greatbritainjpg.jpg" size="227505" originalname="_47061196_greatbritainjpg.jpg" thumbnail="_47061196_greatbritainjpg.jpg" description="No description provided" userid="1" locationid="1" folder="Test_1" /> 
    <file name="Test 1/article-0-07D01B74000005DC-138_468x617.jpg" source="article-0-07D01B74000005DC-138_468x617.jpg" size="143110" originalname="article-0-07D01B74000005DC-138_468x617.jpg" thumbnail="article-0-07D01B74000005DC-138_468x617.jpg" description="No description provided" userid="1" locationid="1" folder="Test_1" /> 
    <file name="Test 1/stags-snow_1544533c.jpg" source="stags-snow_1544533c.jpg" size="21341" originalname="stags-snow_1544533c.jpg" thumbnail="stags-snow_1544533c.jpg" description="No description provided" userid="1" locationid="1" folder="Test_1" /> 
    </files> 

Что я хотел бы сделать так, чтобы изображения загружались пользователем, поэтому, например, «userid» значения «1» в «locationid» значение «1» может просматривать только эти изображения с соответствующими значениями в t он XML-файл.

Я знаю из учебников и статей, которые я прочитал, что заявление Xpath позволяет это сделать. Однако, похоже, существует много разных способов сделать это, и, имея очень, очень мало XML, я действительно не уверен, с чего начать.

Я просто задавался вопросом, может ли кто-нибудь предложить мне какую-то помощь, чтобы помочь мне достичь этого.

С уважением

ответ

1

Нет проблем!

Для вашего утверждения xpath я предполагаю, что вы захотите вернуть имя файла, в котором находится узел xml, который содержит идентификатор пользователя и идентификатор местоположения, который вам нужен.

Таким образом, вы бы сначала начать с корневым узлом, а затем проверить, какой файл имеет этот критерий:

locationid и идентификатор являются оба атрибутами, так что вам нужно использовать символ @, когда ссылки на них в XPath.

$xpath = new DOMXPATH($descriptions) ; 
$result = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@name"); 

Это может выглядеть немного запутанным, так как ваши имена атрибутов являются такими же, как имена входных, но переменные в «». имеют в виду блок:

<input name="userid" type="text" id="userid" value="1" /> 
<input name="locationid" type="text" id="locationid" value="1" /> 

Так что это даст вам имя файла для этого пользователя, который вы могли бы применить к вашему $ исходного тега. Просто повторите заданное xpath и append/@ description или/@ thumbnail вместо имени, чтобы получить другие значения.

Надеюсь, что это поможет, дайте мне знать, если мне нужно что-то прояснить!

Попробуйте это:

(не уверен, где ваша форма ввода пошел в исходном коде, но если вы все еще используете его :)

<ul class="gallery-image-list"> 
        <?php for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) : 
          $name = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@originalname"); 
          $description = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@description"); 
          $folder = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@folder"); 
          $source = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@source");   
          $thumbnail = $xpath->query("files/file[@userid=" . userid . " and @locationid=" . locationid . "]/@thumbnail"); 
        ?> 
        <li class="item"> 
         <a class="fancybox" target="_blank" rel="original" href="<?php echo $source; ?>"><img class="preview" 
         alt="<?php echo $name; ?>" src="<?php echo $thumbnail; ?>" /></a>      </li> 
         <li class="item"></li> 
         <p><span class="style4"><b>Image Description:</b> <?php echo $description;?> <br /> 
          <b>Image contained in folder:</b> <?php echo $folder;?> </span><br /> 

          </li> 
         </p> 
      <?php endfor; ?> 
</ul> 
+0

Привет, спасибо большое за ответ на мой пост. Я добавил строку вверху моего скрипта в разделе '$ description-> load ($ absGalleryPath. 'Files.xml');', но не могли бы вы сказать, пожалуйста, я прав, думая, что есть " В конце концов, линия не закрыта в Dreamweaver? С уважением – IRHM

+0

Ах да, забыли конечные метки, хорошо поймать! Извините, я редактировал свой пост с исправлением. – JWiley

+0

Привет, большое спасибо за подтверждение, было немного догадаться, если честно :) Прошу прощения за это, но я добавил строку '$ result = $ xpath-> query (" файлы/файл [@ userid = ". userid." и @ locationid = ". locationid."]/@ name "); 'в строке 16 в разделе' $ описания-> load ($ absGalleryPath. 'files.xml'); ', но я получаю следующую ошибку:' Fatal error: вызов функции-функции члена() на не-объекте в/homepages /2/d333603417/htdocs/development/gallery.php в строке 16'. Может, объясните, что я сделал неправильно? – IRHM

Смежные вопросы