通过 php 访问子 xml 元素


Access children xml elements through php

问候大家,提前感谢您的回答。所以,我的困难在于,我找到了一个关于 restful 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 的所有元素。谢谢。

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