【问题标题】:Access children xml elements through php [duplicate]通过php访问子xml元素[重复]
【发布时间】:2015-02-23 08:02:36
【问题描述】:

大家好,并提前感谢您的回答。 所以,我的困难在于,我找到了一个关于宁静 Web 服务的不错的教程,但我无法根据自己的需要对其进行修改。

下面的示例代码就像一个魅力

 function get_price($find) {
    $products = array(
        "test" => 293,
        "test2" => 348,
        "test3" => 267
    );

    foreach ($products as $product => $price) {
        if ($product == $find) {
            return $price;
            break;
        }}}

$price 返回对于我通过简单的 html 表单选择的数组的上述每个元素都正确运行。

现在是我的代码

    function get_tickets($find){
    $xml = simplexml_load_file("products.xml");  

    // Here i want to return some of the xml's elements
   }

以及包含的xml文件

<products>
    <company>
        <name>test</name>
        <tel>test</tel>
    </company>
    <products>
        <product id="1">
            <name>test</name>
            <value>test</value>
            <color>test</color>
        </product>
    </products>
</products>

我希望能够像第一个示例代码一样访问 xml 的所有元素。谢谢。

【问题讨论】:

  • 您提出了一个非常笼统的问题。我完全理解您希望能够做到这一点(然后是许多其他事情),但是请先在本网站上搜索这个和/或阅读有关 simplexml 工作原理的文档,例如 @ 987654321@
  • 如果您允许我补充一点意见:在return 之后无需调用break;。如果这是教程的一部分,那么教程包含非常粗略的代码。

标签: php arrays xml web-services restful-url


【解决方案1】:

xpath() 函数应该是你想要的。它返回与给定路径匹配的元素数组。例如,$xml-&gt;xpath("products/products/product") 将为您提供所有 product 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-01-06
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多