2

我目前正在尝试从谷歌联系人 api 中提取信息。使用库中提供的示例代码:

$response = json_encode(simplexml_load_string($val->getResponseBody())); 
$result = json_decode($response, true);

simplexml_load_string功能不会在命名空间上使用。看着 php.net 以及如何添加参数我有点迷茫。

$xml = json_encode(simplexml_load_string(null, $val->getResponseBody(), null, 'gd', true));

尝试从我的 xml 字符串中提取“gd”命名空间的事件我收到一个错误。有没有人可以提供帮助?

输出错误是这样的:

simplexml_load_string() 期望参数 2 是从 SimpleXMLElement 派生的类名

但除了这个错误之外,它还正确打印了我想要的信息......我很困惑。

我需要提取的信息示例:

<gd:extendedProperty xmlns:gs='http://schemas.google_apps_sync.com' name='google_apps_sync'>
    <gs:em_odn1>awalker@xxxxx.com</gs:em_odn1>
    <gs:em_dn1>First Name Last Name</gs:em_dn1>
    <gs:em_ad1>awalker@xxxxxxxxx.com</gs:em_ad1>
    <gs:em_t1>SMTP</gs:em_t1>
    <gs:f_c>32791</gs:f_c>
    <gs:f>Last, First</gs:f>
  </gd:extendedProperty>

编辑

$xmlResponse = simplexml_load_string($val->getResponseBody(), null, 0, 'gd', true);
$xmlResponse->registerXPATHNamespace('gd', 'http://schemas.google_apps_sync.com');
$xmlResponse->registerXPATHNamespace('gs', 'http://schemas.google_apps_sync.com/contact/2008');

上面的代码允许我访问我需要的命名空间,但一次只能访问一个......例如:

$email = json_encode($xmlResponse->xpath('//gd:email'), true));
$postal = json_encode($xmlResponse->xpath('//gd:postalAddress'), true);
$name = json_encode($xmlResponse->xpath('//gs:em_dn1'), true);

$xmlResponse如果我打印这些变量,我会得到我需要的相应信息,但是在我启动了我想要的命名空间之后,有没有办法让我访问原始变量?

前任:

json_decode($xmlResponse, true);

不会给我定义的命名空间的 xml 信息。

4

4 回答 4

2

您可以使用子项获取具有名称空间的元素。例如:

<people xmlns:ns="http://something.com/ns">
<person><ns:name>Amy</ns:name></person>
<person><ns:name>Bill</ns:name></person>
</people>

$xml = simplexml_load_string($string);
echo $xml->person[0]->children("http://something.com/ns")->name; // will echo Amy
于 2015-06-03T16:25:04.163 回答
1

这是手册中所说的

PHP.NET

simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )
$xml = simplexml_load_string($val->getResponseBody(),null, 0, 'gd', true);
$xml =json_encode($xml); 

更新

您没有正确使用命名空间,请显示您的所有 xml 结构。

在您展示的示例中,gd未定义命名空间。你需要这样的东西才能让它工作:

<item xmlns:gd='http://schemas.google_apps_sync.com'> 
   <gd:extendedProperty xmlns:gs='http://schemas.google_apps_sync.com'..>
   ...
   </gd:extendedProperty>
</item>

现在你可以使用

$xml = simplexml_load_string($val->getResponseBody(),null, 0, 'gd', true);

当你想访问gs命名空间时,你可以使用

$xml->registerXPathNamespace("gs", 'http://schemas.google_apps_sync.com');
于 2012-09-05T16:55:03.843 回答
1

经过数小时梳理有关 stackoverflow 的信息并且在 google 上相对未记录的信息后,我发现...如果您添加?alt=json到联系人 api uri 的末尾,您将收到 JSON 格式的响应!

于 2012-09-11T03:41:50.497 回答
0

这会从所有命名空间加载所有数据:

function xmlToArray($xml, $options = array()) {
    $defaults = array(
        'namespaceSeparator' => ':',//you may want this to be something other than a colon
        'attributePrefix' => '@',   //to distinguish between attributes and nodes with the same name
        'alwaysArray' => array(),   //array of xml tag names which should always become arrays
        'autoArray' => true,        //only create arrays for tags which appear more than once
        'textContent' => '$',       //key used for the text content of elements
        'autoText' => true,         //skip textContent key if node has no attributes or child nodes
        'keySearch' => false,       //optional search and replace on tag and attribute names
        'keyReplace' => false       //replace values for above search values (as passed to str_replace())
    );
    $options = array_merge($defaults, $options);
    $namespaces = $xml->getDocNamespaces();
    $namespaces[''] = null; //add base (empty) namespace
    //get attributes from all namespaces
    $attributesArray = array();
    foreach ($namespaces as $prefix => $namespace) {
        foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
            //replace characters in attribute name
            if ($options['keySearch']) $attributeName =
                   str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
            $attributeKey = $options['attributePrefix']
                    . ($prefix ? $prefix . $options['namespaceSeparator'] : '')
                    . $attributeName;
            $attributesArray[$attributeKey] = (string)$attribute;
 
        }
 
    }
 
  
 
    //get child nodes from all namespaces
 
    $tagsArray = array();
 
    foreach ($namespaces as $prefix => $namespace) {
 
        foreach ($xml->children($namespace) as $childXml) {
 
            //recurse into child nodes
 
            $childArray = xmlToArray($childXml, $options);
 
            list($childTagName, $childProperties) = each($childArray);
 
  
 
            //replace characters in tag name
 
            if ($options['keySearch']) $childTagName =
 
                    str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
 
            //add namespace prefix, if any
 
            if ($prefix) $childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
 
  
 
            if (!isset($tagsArray[$childTagName])) {
 
                //only entry with this key
 
                //test if tags of this type should always be arrays, no matter the element count
 
                $tagsArray[$childTagName] =
 
                        in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
 
                        ? array($childProperties) : $childProperties;
 
            } elseif (
 
                is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
 
                === range(0, count($tagsArray[$childTagName]) - 1)
 
            ) {
 
                //key already exists and is integer indexed array
 
                $tagsArray[$childTagName][] = $childProperties;
 
            } else {
 
                //key exists so convert to integer indexed array with previous value in position 0
 
                $tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
 
            }
 
        }
 
    }
 
  
 
    //get text content of node
 
    $textContentArray = array();
 
    $plainText = trim((string)$xml);
 
    if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
 
  
 
    //stick it all together
 
    $propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
 
            ? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
 
    //return node as array
    return array(
        $xml->getName() => $propertiesArray
    );
}
于 2021-12-27T15:16:35.157 回答