Simplexml PHP - 获得"深度节点的价值"

时间:2014-11-25 02:35:33

标签: php xml magento simplexml

这让我发疯了。我可以复制并粘贴我需要的2个值,并且在30分钟前完成了这个,但我试图这样做了#34;正确"。

只有一个"用户名"在整个文件中。我怎么得到它?我尝试使用xpath($username=$xml->xpath('default_setup/connection/username');),我尝试将节点链接到它($ username = $ xml-> {...这里的完整路径...} - > default_setup-> connection-&gt ; username;`)。

当我print_r($xml)时,我可以看到我想要的所有节点及其值。当我print_r($username)我什么都没得到。

<?php
$xml = simplexml_load_file('database.xml',NULL,LIBXML_NOCDATA); // connection details are inside of CDATA

$username=$xml->xpath('default_setup/connection/username'); ?>
<p>Username: <?= (string)$username ?></p><?php // outputs "Array"

<?php
foreach($xml as $element) {
        echo $element . '<br />'; // outputs '<br />' 2 times.
}
?>
<pre>
Username:
<?php print_r($username) ?><?php // nothing ?>
xml:
<?php print_r($xml) ?><?php // full set of all nodes with everything I need just out of reach ?>
</pre>

以下是xml示例。 (实际上是Magento&#34; app / etc / local.xml&#34;文件)

<default_setup>
    <connection>
        <host><![CDATA[localhost]]></host>
        <username><![CDATA[secret_username]]></username>
        <password><![CDATA[secret_password]]></password>
        <dbname><![CDATA[testing_database]]></dbname>
        <initStatements><![CDATA[SET NAMES utf8]]></initStatements>
        <model><![CDATA[mysql4]]></model>
        <type><![CDATA[pdo_mysql]]></type>
        <pdoType><![CDATA[]]></pdoType>
        <active>1</active>
    </connection>
</default_setup>

2 个答案:

答案 0 :(得分:3)

你遗漏了一些你想要的路径链节点:

$conn = $xml->global->resources->default_setup->connection;
$user = (string) $conn->username;
$pass = (string) $conn->password;

你可以在这里使用xpath,但实际上它更麻烦,因为它总会返回一个节点数组(NodeList的表示),所以你必须循环它或使用[0]。只使用直接访问更容易/更易读。那说用xpath做的就是:

$nodes = $xml->xpath('//default_setup/connection');
if (count($nodes) > 0) {
  $conn = $nodes[0];
  $user = (string) $conn->username;
  $pass = (string) $conn->password;
}

来自我的导入程序的完整xml /连接代码,以防它有用:

// get path for config
$config = realpath(dirname(__FILE__) . '/../magento/app/etc/local.xml');

if (!$config) {
    // I've made a terrible mistake.
    throw new Exception('Could not load magento config.');
} else {
    // load up XML
    $conf = new SimpleXMLElement($config, LIBXML_NOCDATA, true);

    // pull the database connection config node
    $conn = $conf->global->resources->default_setup->connection;

    // create a DSN - we will worry about manually setting the attributes ourself
    // since this is a simple one off
    $dsn = sprintf('mysql:host=%s;dbname=%s', $conn->host, $conn->dbname);
    $user = (string) $conn->username;
    $pass = (string) $conn->password;
    $db = new PDO($dsn, $user, $pass);


    if (!$db instanceof PDO) {
        // WOMP, WOMP!
        throw new Exception('Could not create database connection!');
        exit;
    }
}

答案 1 :(得分:0)

让我们远离您的问题以简化事情。这是一个例子。

xml文件,example.php:

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

用于提取情节的PHP代码,在您的情况下将是用户名:

示例#2获取

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

这来自:http://php.net/manual/en/simplexml.examples-basic.php


好吧,好吧,它发生了。

你可以试试这个,特殊值*匹配所有标签。

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>
试一试。这是来自php.net的网址:http://php.net/manual/en/domdocument.getelementsbytagname.php

如果你看下面还有更多的例子。